Jon*_*y-Y 10 emit angularjs angularjs-directive
我试图了解什么是最好的GENERIC方法在父和子指令之间进行通信与隔离范围(它们可能是可重用的项目).
这意味着如果child指令需要以某种方式更新父指令(两者都有隔离的作用域),我应该传递一个回调函数:
例如:
.directive('filterReviewStepBox', function () {
return {
restrict: 'EA',
scop: {
//some data
},
template: '<div>text<reusable-dir></reusable-dir call-back="foo"></div>',
link: function (scope, elem, attrs) {
scope.foo = function () {
console.log('bar');
};
}
};
}).directive('reusableDir', function () {
return {
restrict: 'EA',
scope: {
callBack: '=callBack'
//other data
},
template: '<div>text<button type="button" ng-click="bar"></button></div>',
link: function (scope, elem, attrs) {
scope.bar = function () {
scope.callBack();
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
或者我应该使用$ emit():
例如:
directive('filterReviewStepBox', function () {
return {
restrict: 'EA',
scope: {
// some data
},
template: '<div>text<reusable-dir></reusable-dir></div>',
link: function (scope, elem, attrs) {
scope.$on('foo', function () {
console.log('bar');
});
}
};
}).directive('reusableDir', function () {
return {
restrict: 'EA',
scope: { //some data
},
template: '<div>text<button type="button" ng-click="bar"></button></div>',
link: function (scope, elem, attrs) {
scope.bar = function () {
scope.$emit('foo');
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
我觉得排放更容易理解,但担心性能和开销,但我仍然不确定
试图寻找最好的在线方法,但我仍然st脚
编辑
我忘记了
要求
选项.但我仍然不确定这是最正确的解决方案.因为这不允许我重复使用子或孙,并且使指令成为单个目的项.
为此,最好是利用“require”属性。
指令的完整指南告诉我们有关 require 属性的信息: https: //docs.angularjs.org/api/ng/service/ $compile
需要另一个指令并将其控制器作为第四个参数注入到链接函数中。require 接受要传入的指令的字符串名称(或字符串数组)。
Require 只是告诉指令它应该寻找一些父指令并获取它的控制器。您可以告诉指令使用^前缀在父元素中搜索,并使用?告诉指令是否可以选择此要求。字首。
我修改了您的示例,因此 reusableDir 可以调用 filterReviewStepBox 控制器,但也可以单独使用。
http://jsbin.com/gedaximeko/edit?html,js,控制台,输出
angular.module('stackApp', [])
.directive('filterReviewStepBox', function () {
return {
restrict: 'EA',
scope: {
// some data
},
template: '<div>text<reusable-dir></reusable-dir></div>',
link: function (scope, elem, attrs) {
},
controller : function() {
this.notify = function(value) {
console.log('Notified : ' + value);
};
},
controllerAs: 'vm',
bindToController: true
};
}).directive('reusableDir', function () {
return {
restrict: 'EA',
scope: { //some data
},
require: '?^filterReviewStepBox',
template: '<div>text<button type="button" ng-click="bar()"></button></div>',
link: function (scope, elem, attrs, controller) {
scope.bar = function () {
if (controller) {
controller.notify('foo');
}
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1656 次 |
| 最近记录: |