在我的 Angular 应用程序中,我有一些嵌套的 ng-repeats 来解析一些预期的 JSON 对象,例如:
{
landAnimals: {
horse: {
sound: "Nay",
legs: 4,
},
beaver: {
sound: "thwack",
legs: 2
}
},
waterAnimals: {
dolphin: {
sound: "Eee",
fins: 3,
},
goldfish: {
sound: "-",
fins: 1
}
}
}
在某一时刻,我想做的是将动物类别传递给我的指令,并将另一个动物对象传递给它。
例如,如果用户将另一个动物拖动到我的应用中生成的列表中,我想将他拖动的动物添加到上面的 JSON 中。
为此,我尝试将动物对象传递给指令,然后向其中添加新动物。
例如:
<div ng-repeat="animalCategory in animals on-drop-success='animalCategory'">
<div ng-repeat="(key, value) in animalCategory">
{{key}}
</div>
</div>
然后在我的 onDropSuccess
指令中,在 link
函数中,我尝试
(不用担心我是如何进行拖放的,即使是这个简单的测试它也不起作用)
...
link: function (scope, element, attrs) {
attrs.onDropSuccess["newAnimal"] = {sound: "miy", legs: 2};
...
总而言之,我尝试将 animalCategory
对象传递给我的指令,以便我可以在其下添加更多对象。但这不起作用。即使我手动提供一个简单的对象(即它与拖动实现无关),它也不会添加对象
有什么想法为什么会发生这种情况吗?
最佳答案
目前,您没有引用实际对象,只是引用 attrs
上的属性。构造将返回一个字符串。
您可以通过多种方式获取实际引用。
//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);
在 Isolate Scope 上使用 =
参数
您可以使用scope
将参数拉入指令隔离范围。指令定义上的属性。
{
scope:{
onDropSuccess: '='
}
link: function(scope, elem, attrs){
//Basically same as above, except that they
// are pulled from the parent scope
var targetObject = scope.onDropSuccess;
}
}
关于javascript - 如何将实际对象(即对象的引用)传递给指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27106661/