我有一个对象,它由多个数组组成:
$scope.myArrays = {
array1: ['Pizza', 'Spaghetti'],
array2: ['Lasagne', 'Schnitzel']
};
此外,我有一个自定义的指令,我希望将此对象 myArrays
和将这些数组绑定到范围变量:
<my-directive my-data="myArrays"></my-directive>
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
arrayOne: '=myData.array1',
arrayTwo: '=myData.array2'
},
link: function(scope, elem) {
// get access to scope.array1 and scope.array2
}
};
});
All together in a fiddle for you to play around!
有没有办法直接绑定数组,还是需要绑定arrays: '=myArrays'
并像arrays.array1
那样访问它们?
答案 0 :(得分:2)
绑定必须是一对一的,你不能这样做。是的,您必须访问指令中的数组。
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myData: '='
},
link: function(scope, elem) {
scope.arrayOne = scope.myData.array1;
scope.arrayTwo = scope.myData.array2;
}
};
});
如果您不必在链接函数中处理这些数组并将其删除,您可以直接访问指令模板中的scope.myData.array1
和scope.myDate.array2
。
答案 1 :(得分:0)
您可以通过将它们分配到scope
字段来实现此目的:
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myData: '='
},
link: function(scope, elem) {
scope.arrayOne = myData.array1;
scope.arrayTwo = myData.array2;
}
};
});
但是,我建议只绑定对象并摆脱link
- 函数。这样,指令代码更短,更易读,更少“黑魔法”发生,指令内的引用更具表现力:
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myData: '='
}
};
});
然后您可以使用myData.array1
在指令中引用它。将'='
替换为'=someName'
,以someName.array1
答案 2 :(得分:0)
你的HTML应该是:
.eq()
和你的指令:
<my-directive arrayone="myData.array1" arraytwo="myData.array2"></my-directive>
答案 3 :(得分:0)
HTML的部分:
<div ng-controller="MyCtrl">
<my-directive my-data="myArrays" array-one="myArrays.array1" array-two="myArrays.array2">
</my-directive>
</div>
脚本:
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
arrayOne: '=',
arrayTwo: '='
},
link: function(scope, elem) {
// get access to scope.array1 and scope.array2
//console.log(scope.array1)
console.log(scope.arrayOne);
console.log(scope.arrayTwo);
}
};
})
.controller('MyCtrl', function($scope) {
$scope.myArrays = {
array1: ['Pizza', 'Spaghetti'],
array2: ['Lasagne', 'Schnitzel']
};
});