问题1.
由于是向acts数组中添加项,所以需要将$watch()中的第三个参数设置为true
$scope.$watch('acts', function (neww, old) {
console.log(neww)
}, true);
演示:小提琴
问题2.
既然有一个隔离作用域,就需要调用$parent作用域的函数
<input type="button" bn="" acts="acts" ng-click="$parent.addaction()" value="Add Action" />
演示:小提琴
问题 3.
可以,但需要使用控制器
animateAppModule.directive('bn', function () {
return {
restrict: "A",
scope: {
acts: '='
},
link: function ($scope, iElement, iAttrs) {
$scope.$watch('acts', function (neww, old) {
console.log(neww)
}, true)
},
controller: function($scope){
$scope.dosomething = function(){
console.log('do something')
}
}
}
})
演示:小提琴
整体解决方案可能看起来像
<input type="button" bn="" acts="acts" addaction="addaction()" value="Add Action" />
JS
animateAppModule.controller('tst', function ($scope) {
$scope.acts = [];
$scope.addaction = function () {
$scope.acts.push({
a: "a,b"
})
}
})
animateAppModule.directive('bn', function () {
return {
restrict: "A",
scope: {
acts: '=',
addaction: '&'
},
link: function ($scope, iElement, iAttrs) {
$scope.$watch('acts', function (neww, old) {
console.log(neww)
}, true);
iElement.click(function(){
$scope.$apply('addaction()')
})
}
}
})
演示:小提琴