我对 Angular 指令还很陌生,我很难让它做我想做的事。这是我所拥有的基础知识:
Controller :
controller('profileCtrl', function($scope) {
$scope.editing = {
'section1': false,
'section2': false
}
$scope.updateProfile = function() {};
$scope.cancelProfile = function() {};
});
指令:
directive('editButton', function() {
return {
restrict: 'E',
templateUrl: 'editbutton.tpl.html',
scope: {
editModel: '=ngEdit'
}
};
});
模板(editbutton.tpl.html):
<button
ng-show="!editModel"
ng-click="editModel=true"></button>
<button
ng-show="editModel"
ng-click="updateProfile(); editModel=false"></button>
<button
ng-show="editModel"
ng-click="cancelProfile(); editModel=false"></button>
HTML:
<edit-button ng-edit="editing.section1"></edit-button>
如果不清楚,我要 <edit-button>
包含三个不同按钮的标签,每个按钮都与传入 ng-edit
的范围属性进行交互.单击时,他们应该更改该属性,然后调用适当的范围方法。
现在的情况是,单击按钮会正确更改 $scope.editing
的值,但是 updateProfile
和 cancelProfile
方法不起作用。我可能偏离了如何正确使用指令的基础,但我很难在网上找到一个示例来帮助我完成我想做的事情。任何帮助将不胜感激。
最佳答案
一种方法是使用 $parent
调用函数。
<button ng-show="editModel" ng-click="$parent.cancelProfile(); editModel=false">b3</button>
另一种方法(可能是更好的方法)是配置指令的隔离作用域以包含对这些 Controller 函数的引用:
app.directive('editButton', function() {
return {
restrict: 'E',
templateUrl: 'editbutton.tpl.html',
scope: {
editModel: '=ngEdit',
updateProfile: '&',
cancelProfile: '&'
}
};
});
然后通过 HTML 传递函数:
<edit-button ng-edit="editing.section1" update-profile='updateProfile()' cancel-profile='cancelProfile()'></edit-button>
关于javascript - AngularJs 指令 : call method from parent scope within template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24513564/