我使用“=”方法制作了带隔离范围的指令,在该指令中我传递空数组,然后我在该数组上推送数据....如何在我的控制器中的原始数组上反映出这种变化?
以下是示例:
angular.module('myModule').controller('MyController', ['$scope', function($scope) {
$scope.test = [];
}]);
angular.module('myModule').directive('mydirective', function() {
return {
scope: {
test: "=",
bread: "="
},
restrict: 'E',
link: function(scope, element, attribute) {
scope.test.push('one more')
},
replace: true,
templateUrl: 'some template'
};
});
HTML
<div ng-controller='MyController'>
<mydirective test='test'></mydirective>
<div ng-bind='test'> </div>
</div>
当我在阵列上推送某些东西时,我的控制器中没有反映出来的东西。 我该如何解决?
答案 0 :(得分:0)
以下是如何做到你想要实现的目标。
HTML 的
<!-- myCtrl contains the original array, which we push here to the scope as 'ctrl' -->
<div ng-controller='myCtrl as ctrl'>
<!-- we pass your directive 'ctrl.test', which tells angular to two-way bind to the
test property on the 'ctrl' object on the current scope -->
<mydirective test='ctrl.test'>
<!-- we're inside the isolate scope: test here refers to mydirective's idea of test,
which is the two-way bound array -->
<div ng-bind='test'></div>
</mydirective>
</div>
JS
angular.module('app', [])
.directive('mydirective', function() {
scope: {
test: '='
},
link: function($scope) {
$scope.test.push('one more');
}
})
.controller('myCtrl', function() {
this.test = [];
});
对阵列的任何更改现在都会反映在ng-bind
中。请注意,在$scope
上放置基元而不是对象的一部分(由于原型继承的机制)是不好的做法,因此您需要将$scope.test
更改为其他内容。