javascript – AngularJs指令:从模板中的父作用域调用方法

我对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的值,但updateProfile和cancelProfile方法不起作用.我可能会偏离如何正确使用指令,但我在网上找到一个例子来帮助我完成我想要做的事情.任何帮助,将不胜感激.

解决方法

一种方法是使用$parent调用函数.
<button ng-show="editModel" ng-click="$parent.cancelProfile(); editModel=false">b3</button>

Demo

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

app.directive('editButton',scope: {
      editModel: '=ngEdit',updateProfile: '&',cancelProfile: '&'
    }
  };
});

然后通过HTML传递函数

<edit-button ng-edit="editing.section1" update-profile='updateProfile()' cancel-profile='cancelProfile()'></edit-button>

Demo

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面