【发布时间】:2017-07-12 23:24:14
【问题描述】:
我正在尝试实现嵌套指令。内部指令是一个在 ng-click 中调用函数的按钮。模型中定义了要调用的函数名称。
首先,这里是 plunker 链接。 PLUNKER
问题是按钮不知道要调用的函数。 有趣的是,如果我使用 ng-include 和在范围内正确命名的变量为外部指令使用模板,它就像一个魅力。
为您准备的一些代码片段:
index.html:
DIRECTIVES
<outer-directive functions="functions" datas="datas"></outer-directive>
<p>{{clicked}}</p>
NG-Include :
<div ng-include src="'outer-template.html'"></div>
外部指令模板
<div ng-repeat="d in datas">
Hi, {{d}}
<inner-directive
ng-repeat="funct in functions"
text="funct.text"
method="this[funct.method](d)">
</inner-directive>
</div>
控制器
app.controller('MainCtrl', function($scope) {
$scope.datas = [0, 1];
$scope.functions = [{
method: 'functOne',
text: 'Funct One'
}, {
method: 'functTwo',
text: 'Funct Two'
}];
$scope.clicked = 'Nothing happend';
$scope.functOne = function(data) {
$scope.clicked = data + ' pressed Funct 1';
}
$scope.functTwo = function(data) {
$scope.clicked = data + ' pressed Funct 2';
}
});
外部指令 JS
app.directive('outerDirective', function() {
return {
restrict: 'E',
scope: {
functions: '=',
datas: '='
},
templateUrl: 'outer-template.html'
}
});
内部指令 JS
app.directive('innerDirective', function() {
return {
restrict: 'E',
scope: {
method: '&',
text: '=',
datas: '='
},
template: '<button ng-click="method(datas)"> {{text}}</button>'
}
});
【问题讨论】:
-
所以,我决定使用 $emit 和 $on(参见 this question)
标签: angularjs angularjs-directive angularjs-ng-repeat angularjs-ng-click angularjs-ng-include