我有一个带有控制器的父指令,它在$scope上设置了一个方法。
然后,在子指令中,我尝试通过&
要求scope方法。
然而,子指令中的ng-click
不会通过父作用域函数触发。我做错了吗?
父指令(其中定义了方法)
app.directive('ParentDirective', [
'$http',
function($http) {
return {
restrict: 'AE',
template: '' +
'<div child-directive ' +
'list="list" ' +
'/>' +
'',
controller: function ($scope, $http) {
$scope.setSelected = function (selector) {
console.log('hit!', selector);
}
$scope.list = [];
},
link: function postLink(scope, element, attrs) {}
};
}
]);
子指令(尝试在ng-click上调用父方法,但不工作)
app.directive('childDirective', [
'$window',
function($window) {
return {
restrict: 'AE',
scope: {
setSelected: '&',
list: '=',
},
template: '' +
'<ul>' +
'<li ng-repeat="person in list" ng-click="setSelected(person)">{{person.uri}}</li>' +
'</ul>' +
'',
link: function postLink(scope, element, attrs) {
}
};
}
]);
我传递$scope.setSelected()
错误从父到子指令?
EDIT:所以我改变了父模板,像这样分配函数:模板:"+" +",
现在将触发该函数,但参数不会从子指令传递。我怎样才能让子指令传递一个参数到父指令函数?
ParentDirective有打字错误,应该是:ParentDirective
在parentDirective模板中你应该传递函数'list="list" ' + 'set-selected="setSelected(person) "
试试这个:html:
<parent-directive ></parent-directive>
js:
app.directive('parentDirective', [
'$http',
function($http) {
return {
restrict: 'AE',
template: '' +
'<div child-directive ' +
'list="list" ' + 'set-selected="setSelected(person)"'+
'/>' +
'',
controller: function ($scope, $http) {
$scope.setSelected = function (selector) {
console.log('hit!', selector);
}
$scope.list = [];
},
link: function postLink(scope, element, attrs) {}
};
}
])
app.directive('childDirective', [
'$window',
function($window) {
return {
restrict: 'AE',
scope: {
setSelected: '&',
list: '=',
},
template: '' +
'<ul>' +
'<li ng-repeat="person in list" ng-click="setSelected({person:person})">{{person.uri}}</li>' +
'</ul>' +
'',
link: function postLink(scope, element, attrs) {
}
};
}
]);
工作恰好:
https://plnkr.co/edit/KUWZ9bYbhnbumFwIgcIX?p =预览