AngularJS指令:如何在模板中调用父作用域中的方法

6

我对Angular指令还很陌生,正在尝试实现自己想要的功能时遇到了很多问题。以下是我的基本代码:

控制器:

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的值,但updateProfilecancelProfile方法不起作用。我可能完全错了如何正确使用指令,但我很难找到一个在线示例来帮助我完成我想要做的事情。任何帮助都将不胜感激。
1个回答

17

一种方法是使用$parent来调用函数。

<button ng-show="editModel" ng-click="$parent.cancelProfile(); editModel=false">b3</button>

演示

另一种(也可能更好的)方法是配置指令的隔离作用域来包含对那些控制器函数的引用:

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>

演示


太好了,谢谢。我倾向于使用您的第一个示例,因为这两种方法在指令中始终相同,并且可以减少不必要的HTML。您为什么说第二种方法是“更好的方法”? - Will Durney
1
@futurityverb,第二种方法更通用。如果您想要一个具有略微不同行为的指令实例,只需传入应调用的不同方法即可。此外,如果您开始将指令嵌套在其他指令中,则$parent可能不再引用控制器作用域,而是某些其他中间作用域。 - Jerrad
1
引导我朝着正确的方向前进,但如果我想使用您的第二个示例将参数传递给方法怎么办? - Alex McCabe
将您的参数作为对象传递。像这样:update-profile='updateProfile({message: testMessage})' - Jerrad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接