如果问题请参考这个小提琴.http://jsfiddle.net/AQR55/
1)为什么连接到隔离范围属性的手表(双向绑定到父属性)不会在更改父范围属性时触发.
在小提琴中,在更改绑定的父范围属性时,下面提到的监视不会被触发.
$scope.$watch('acts', function(neww ,old){
console.log(neww)
})
Run Code Online (Sandbox Code Playgroud)
2)ng-click="addaction()" addaction="addaction()"
.这段代码能以更优雅的方式呈现吗?因为,要在隔离范围内执行操作,我们似乎需要设置双向绑定和附加到ng-click.
3)我可以在隔离范围内声明方法,如下所示吗?如果我这样做,我会得到.js错误.
<isolate-scope-creating-cmp ng-click="isolateCmpClickHandler()"></isolate-scope-creating-cmp>
scope:{
isolateCmpClickHandler:function(){
//If i do like this, I'm getting .js error
}
}
Run Code Online (Sandbox Code Playgroud)
Aru*_*hny 22
问题1.
由于要向acts
数组添加项,因此需要将$ watch()中的第三个参数设置为true
$scope.$watch('acts', function (neww, old) {
console.log(neww)
}, true);
Run Code Online (Sandbox Code Playgroud)
演示:小提琴
问题2.
由于存在隔离范围,因此需要调用$parent
范围的功能
<input type="button" bn="" acts="acts" ng-click="$parent.addaction()" value="Add Action" />
Run Code Online (Sandbox Code Playgroud)
演示:小提琴
问题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')
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
演示:小提琴
整体解决方案可能看起来像
<input type="button" bn="" acts="acts" addaction="addaction()" value="Add Action" />
Run Code Online (Sandbox Code Playgroud)
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()')
})
}
}
})
Run Code Online (Sandbox Code Playgroud)
演示:小提琴