javascript - 从带参数的指令调用 Controller 函数

标签 javascript angularjs angularjs-directive

指令如何使用某些参数从 Controller 调用函数?

我会将变量 myVar 赋予作用域。$apply(attrs.whattodo);

HTML:

<div ng-app="component">
  <div ng-controller="ctrl">
    <span ng-repeat="i in myarray">
     <span  customattr  whattodo="addVal">{{i}}</span>
    </span>
  </div>

Controller JS:

   function ctrl($scope) {
      $scope.myarray = [1];
      $scope.addVal = function (value) {
          $scope.myarray.push(value);
      }
   }

指令 JS:

angular.module('component', []).directive('customattr', function () {
  return {
      restrict: 'A',
      link: function (scope, element, attrs) {
          var myVar = 5;
          scope.$apply(attrs.whattodo);
      } 
  }; 
}); 

最佳答案

这是其中一种工作方法:

您必须在作用域中将此属性绑定(bind)为具有函数类型的作用域模型。因此,当您需要其他(指令)sope时,您可以执行此操作

HTML

<body ng-controller="MainCtrl">
  Value: {{value}}!

  <button customattr whattodo="addValue">Add</button>
</body>

JS

angular.module('component', [])

.controller('MainCtrl', function($scope) {
  $scope.value = 1;

  $scope.addValue = function(val){
    alert(val);
    $scope.value = val;
  }
});

.directive('customattr', function () {
  return {
      restrict: 'A',
      scope: {
          whattodo: "=" // or ' someOtherScopeName: "=whattodo" '
      },
      link: function (scope, element, attrs) {
          var myVar = 5;
          scope.whattodo(myVar); // or ' scope.someOtherScopeName(myVar) '
      } 
  }; 
});

这里是code on plunker

from AngularJS: Directives

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localModel:'=myAttr' }, then widget scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected in localModel and any changes in localModel will reflect in parentModel

关于javascript - 从带参数的指令调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135711/

相关文章:

javascript - 适用于 Android、iOS 和 Windows 平板电脑的 Cordova 滑动事件检测选项

javascript - 删除 ng-show 泄漏 $watch

angularjs - 将文字属性值传递给 angular js 指令

angularjs - 如何在移动应用程序中使用 SAML 身份验证?

angularjs - 获取 apiKey 到 firebase

Javascript:封装和抽象

Javascript - 是否可以缓存元素的内部 html,以便在页面刷新后我可以渲染缓存的元素?

javascript - 自定义指令中范围对象内的嵌套对象

javascript - .show() 导致可滚动 DIV 在 Firefox 中跳转到顶部

javascript - 将 json 数组格式化为图表输入