【问题标题】:AngularJs directive: call method from parent scope within templateAngularJs 指令:从模板内的父范围调用方法
【发布时间】:2014-07-01 15:04:51
【问题描述】:

我对 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>

如果不清楚,我希望&lt;edit-button&gt; 标记包含三个不同的按钮,每个按钮与传递给ng-edit 的任何范围属性交互。单击时,他们应该更改该属性,然后调用适当的范围方法。

现在的情况是,单击按钮会正确更改$scope.editing 的值,但updateProfilecancelProfile 方法不起作用。我可能无法正确使用指令,但我无法在网上找到一个示例来帮助我完成我想做的事情。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript angularjs templates scope directive


    【解决方案1】:

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

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

    Demo

    另一种方法(可能是更好的方法)是配置指令的隔离范围以包含对这些控制器函数的引用:

    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>
    

    Demo

    【讨论】:

    • 太好了,谢谢。我倾向于使用您的第一个示例,因为这两种方法在指令之间总是相同的,并且会减少无关的 html。是什么让您说第二种方式是“更好的方式”?
    • @futurityverb,第二种方法更通用。如果你想要一个行为稍有不同的指令实例,你可以传入一个应该被调用的不同方法。此外,如果您开始将指令嵌套在其他指令中,$parent 可能不再指代控制器范围,而是其他一些中间范围。
    • 将我推向了正确的方向,但是如果我想使用您的第二个示例将参数传递给方法怎么办?
    • 将您的论点作为对象传入。像这样的东西:update-profile='updateProfile({message: testMessage})'.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    相关资源
    最近更新 更多