处理'&'和孤立的范围。
是否可以通过父指令传递值?我想将id从textdisp指令传递给控制器。
HTML:
<body ng-controller="MainCtrl">
<builder removequest="deleteQuestion(id)"></builder>
</body>
ANGULAR:
app.controller('MainCtrl', function($scope) {
$scope.deleteQuestion = function(id) {
alert(id);
}
});
app.directive('builder', function() {
return {
restrict: 'E',
scope: {
removequest: '&'
},
template: '<div>Hello how are you? <textdisp removequest=removequest(id)></textdisp></div>'
}
});
app.directive('textdisp', function() {
return {
restrict: 'E',
scope: {
removequest: '&'
},
template: '<div ng-click="remove()">Click here!</div>',
link: function (scope, el) {
scope.remove = function(id) {
console.log('workin')
scope.removequest(1);
}
}
}
});
答案 0 :(得分:1)
我相信您的代码会发生两件事:
removequest="removequest(id)"
时,而不只是引用该函数。&attr
绑定没有返回您期望的功能。 Try this Plunker;它本质上使用{ removequest: '=' }
进行双向绑定,使用removequest="deleteQuestion"
/ removequest="removequest"
进行函数引用,而不是调用函数。
答案 1 :(得分:1)
这有点令人困惑,但是当您需要将值传递到通过&
绑定调用的函数时,可以使用object参数。看看这段代码,它将使一切清晰:
app.controller('MainCtrl', function($scope) {
$scope.deleteQuestion = function(id) {
alert(id);
}
});
app.directive('builder', function() {
return {
restrict: 'E',
scope: {
removequest: '&'
},
template: '<div>Hello how are you? <textdisp removequest="removequest({id: id})"></textdisp></div>'
}
});
app.directive('textdisp', function() {
return {
restrict: 'E',
scope: {
removequest: '&'
},
template: '<div ng-click="remove()">Click here!</div>',
link: function(scope, el) {
scope.remove = function(id) {
scope.removequest({id: 34534}); // <-- 1.
}
}
}
});
请注意您如何指定要传递到scope.removequest({id: 34534})
的{{1}}参数。