Reputation: 23312
In my Angular app, I have a few nested ng-repeats to parse through some expected JSON objects, for example:
{
landAnimals: {
horse: {
sound: "Nay",
legs: 4,
},
beaver: {
sound: "thwack",
legs: 2
}
},
waterAnimals: {
dolphin: {
sound: "Eee",
fins: 3,
},
goldfish: {
sound: "-",
fins: 1
}
}
}
At one point, what I would like to do is pass the animal category to my directive and another animal object to it.
For example, if a user drags another animal into the list that is generated in my app, I want to add the animal he dragged into the JSON above.
To do this, I'm trying to pass the animal object to a directive and then adding the new animal to it.
For instance:
<div ng-repeat="animalCategory in animals on-drop-success='animalCategory'">
<div ng-repeat="(key, value) in animalCategory">
{{key}}
</div>
</div>
and then in my onDropSuccess
directive, in the link
function, I am trying
(don't worry about how I'm doing the drag and drop, it's not working even with this simple test)
...
link: function (scope, element, attrs) {
attrs.onDropSuccess["newAnimal"] = {sound: "miy", legs: 2};
...
To summarize, I am trying to pass the animalCategory
object to my directive so I can add more objects under it. But it's not working. It doesn't add the object even when I manually provide a naive object (i.e. it has nothing to do with the drag implementation)
Any ideas why this is happening?
Upvotes: 1
Views: 106
Reputation: 44906
At the moment, you aren't referencing an actual object, only a property on the attrs
construct that will return a string.
There are a couple of ways you could pull in an actual reference.
Using scope.$eval
//Target object will be pulled in if it exists on the scope
// this will not work if you are using Isolate Scope
var targetObject = scope.$eval(attrs.onDropSuccess);
Using =
parameters on Isolate Scope
You can pull in parameters into the directives isolate scope by using the scope
property on the directive definition.
{
scope:{
onDropSuccess: '='
}
link: function(scope, elem, attrs){
//Basically same as above, except that they
// are pulled from the parent scope
var targetObject = scope.onDropSuccess;
}
}
Upvotes: 1