我试图从范围隔离指令中调用范围函数, 这是我的代码:
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
我做得对吗,还是这是一个棱角分明的反模式?
答案 0 :(得分:1)
在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>