CodyBugstein
CodyBugstein

Reputation: 23372

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.

Upvotes: 0

Views: 453

Answers (2)

arghya
arghya

Reputation: 123

you can use isolate scope. Assuming the array of animals is a scope property of the parent controller, you can do this:

<div ng-repeat="animal in animals">
    <animal this-animal="animal"></animal>
</div>

And in the directive code:

module.directive('myDirective', function() {
    return {

        scope: {
            thisAnimal: "="
        },

        link: function(scope, element, attrs) {
            scope.thisAnimal.gestation = 10;
        }
    };
});

Refer the isolate scope section of this page for more details:

https://docs.angularjs.org/guide/directive

Upvotes: 1

Enzey
Enzey

Reputation: 5254

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);
        }
    };
});

Upvotes: 1

Related Questions