Search code examples
javascriptjsonangularjsangular-directive

How do you pass an object reference to a directive?


In my app, I have an ng-repeat that iterate through JSON and prints each object to the page. So for example, my ng-repeat prints the animals

[
              {
                   name: "horse",
                   sound: "Nay",
                   legs: 4,
              },
              {
                    name: "beaver",
                    sound: "thwack",
                    legs: 2
              }
]

I also want to pass each animal to a directive and possibly add some key, values to them. The problem is, when I add the animal object as an attribute and update it in the directive,

i.e.

<animal this-animal={{animal}}></animal>

and in the directives link function

var animalObj = scope.$eval(attrs.thisAnimal);
animalObj["gestation"] = 10;

it doesn't update in the original JSON. It's like it gets disconnected from the overall array of all animals.

Why? How do I keep it all together? I want updates to individual objects to make changes in the main JSON object.


Solution

  • By using {{model}} in html it will resolve that value and place it into the HTML. In your case the JSON is getting stringified and then coverted back thus making a cloned object. Instead of using {{model}} just pass the name of the value.

    <div my-directive="model">
    

    Then access the model value using $parse

    module.directive('myDirective', function($parse) {
        return {
            link: function(scope, element, attrs) {
                var val = $parse(attrs.my directive)(scope);
            }
        };
    });