我试图从范围隔离指令内部调用范围函数,下面是我的代码:
angular.module('directive', [])
.directive('dirz', function() {
return {
restrict:'E',
link: function(scope, elm, attrs, ctrl) {
},
controller: function() {
}
};
})
.directive('dir1', function() {
return {
require: 'dirz',
scope:{},
link: function(scope, elm, attrs, ctrl) {
}
};
})
.directive('dir2', function() {
return {
restrict:'E',
link: function(scope, elm, attrs, ctrl) {
// this function is never called bacause of isolated scope ?
scope.click = function(){
console.log("somebody clicked me!!");
}
}
};
});
和我的html
<dirz dir1>
<!-- I want to call click scope function in dir2 -->
<button ng-click="click()">click</button>
</dirz>
<dir2></dir2>
这是一个plunk
我这样做对吗?还是这是一个有角度的反模式?
click()
处理程序在dir1
的隔离作用域中不可访问。
触发两个点击,移动按钮HTML到你的指令的模板(模板将被链接到隔离的范围),然后调用$broadcast发送消息给dir2
。这可能是你最好的选择,因为div彼此是兄弟姐妹,而不是父母/孩子关系。
.directive('dir1', function() {
return {
require: 'dirz',
template: '<button ng-click="click()">click</button>',
controller: function($scope, $rootScope) {
$scope.click = function() {
console.log('somebody clicked me');
$rootScope.$broadcast('click');
}
},
scope:{},
link: function(scope, elm, attrs, ctrl) {
}
};
})
.directive('dir2', function() {
return {
restrict:'E',
link: function(scope, elm, attrs, ctrl) {
// this function is never called bacause of isolated scope ?
scope.$on('click', function() {
console.log('received click message');
});
}
};
});
HTML <dirz dir1>
</dirz>
<dir2>
</dir2>