Wil*_*ney 6 javascript templates scope directive angularjs
我对Angular指令很新,而且我很难做到这样做我想做的事情.这是我所拥有的基础知识:
控制器:
controller('profileCtrl', function($scope) {
$scope.editing = {
'section1': false,
'section2': false
}
$scope.updateProfile = function() {};
$scope.cancelProfile = function() {};
});
Run Code Online (Sandbox Code Playgroud)
指示:
directive('editButton', function() {
return {
restrict: 'E',
templateUrl: 'editbutton.tpl.html',
scope: {
editModel: '=ngEdit'
}
};
});
Run Code Online (Sandbox Code Playgroud)
模板(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>
Run Code Online (Sandbox Code Playgroud)
HTML:
<edit-button ng-edit="editing.section1"></edit-button>
Run Code Online (Sandbox Code Playgroud)
如果不清楚,我希望<edit-button>标签包含三个不同的按钮,每个按钮与传入的任何范围属性进行交互ng-edit.单击时,它们应更改该属性,然后调用相应的范围方法.
现在的方式,单击按钮正确更改值$scope.editing,但updateProfile和cancelProfile方法不起作用.我可能会偏离如何正确使用指令,但我在网上找到一个例子来帮助我完成我想要做的事情.任何帮助,将不胜感激.
Jer*_*rad 16
一种方法是使用调用函数$parent.
<button ng-show="editModel" ng-click="$parent.cancelProfile(); editModel=false">b3</button>
Run Code Online (Sandbox Code Playgroud)
另一种方式(可能更好的方法)是配置指令的隔离范围以包含对这些控制器函数的引用:
app.directive('editButton', function() {
return {
restrict: 'E',
templateUrl: 'editbutton.tpl.html',
scope: {
editModel: '=ngEdit',
updateProfile: '&',
cancelProfile: '&'
}
};
});
Run Code Online (Sandbox Code Playgroud)
然后通过HTML传递函数:
<edit-button ng-edit="editing.section1" update-profile='updateProfile()' cancel-profile='cancelProfile()'></edit-button>
Run Code Online (Sandbox Code Playgroud)