javascript - AngularJs 指令 : call method from parent scope within template

标签 javascript angularjs templates scope directive

我对 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 的值,但是 updateProfilecancelProfile方法不起作用。我可能偏离了如何正确使用指令的基础,但我很难在网上找到一个示例来帮助我完成我想做的事情。任何帮助将不胜感激。

最佳答案

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

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

Demo

另一种方法(可能是更好的方法)是配置指令的隔离作用域以包含对这些 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>

Demo

关于javascript - AngularJs 指令 : call method from parent scope within template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24513564/

相关文章:

javascript - 从另一个 Controller 调用函数

c++ - 试图更好地理解 std::forward、std::move

javascript - 将鼠标悬停在导航链接上时如何防止持续闪烁?

javascript - 如何定位交替的奇数/偶数文本行

javascript - 如何在 ServiceWorker 中处理 Session 过期

javascript - 如何阻止函数在 x 秒结束之前返回新结果,并在调用太快时返回之前的结果

javascript - Angular 将字符串传递给函数

angularjs - 如何部署 yeoman angular-fullstack 项目?

templates - 如何在golang中定义匿名数据结构

c++ - std::is_base_of 用于模板类