嵌套指令中的变量函数名称



我正在尝试实现嵌套指令。内部指令是一个按钮,它在 ng-click 中调用函数。要调用的函数的名称在模型中定义。

首先,这里是 plunker 链接。普容克

问题是按钮不知道要调用的函数。 有趣的是,如果我使用 ng-include 和作用域中正确命名的变量为外部指令使用模板,它就像一个魅力。

为您提供一些代码片段:

索引.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>'
}
});

在从指令到控制器的回调函数中,参数应作为对象传递。

这是演示 plunker 点击这里

希望它有助于理解如何通过回调函数将参数从指令传递到控制器。

现在前进到嵌套指令:需要遵循相同的过程来跨指令传递参数,从而最终传递给控制器。

让控制器成为

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(id){
$scope.clicked = id + ' .....pressed Funct 1';
}
$scope.functTwo = function(id){
$scope.clicked = id + ' ....pressed Funct 2';
}
});

外层二重奏

app.directive('outerDirective', function() {
return {
restrict: 'E',
scope: {
outer: '&',
datas: '='
},
templateUrl: 'outer-template.html',
}
});

内部指令

app.directive('innerDirective', function() {
return {
restrict: 'E',
scope: {
inner: '&',
text: '=',
data: '='
},
template: '<button ng-click="clickMe()">click here</button>',
link: function (scope, element, attrs) {
scope.clickMe=function(){
scope.inner({id:'hello... data is ' + scope.data });
}
}
}
});

.HTML

<body ng-controller="MainCtrl">
<div ng-repeat="func in functions">
<outer-directive outer=$eval(func.method)(term) datas="datas"></outer-
directive>
</div>
<p>{{clicked}}</p>
</body>

模板

<div ng-repeat="d in datas">
<inner-directive inner="outer({term: id})" data="d"></inner-directive>
</div>

这是工作褶皱机

最新更新