将函数从父控制器传递给带有参数的指令

pass function from parent controller to directive with parameter

我想问一下在AngularJS中将函数从控制器传递到指令的方法。

父控制器中有 2 个 foo,它们的工作方式几乎相同(在实际代码中略有不同)所以我决定将它们放在父控制器中并将 variable/function 传递给指令。

没有参数的函数没有问题,但像$scope.func1 = function(index) { // bla bla }这样的函数无法传递给指令。

你能帮我解决这个问题吗?

欢迎任何建议和解决方案:)

视图和控制器

view.html

<my-directive lists="foo1" 
              item-click="showFoo1List()" 
              show="showFoo1" 
              func="func1"> <!-- I want to pass this one -->
</my-directive>
<my-directive lists="foo2" 
              item-click="showFoo2List()" 
              show="showFoo2" 
              func="func2">  <!-- this one -->
</my-directive>

controller.js

angular.module('app')
.controller('MyCtrl', function($scope){
  // Foo1
  $scope.foo1 = [ { name: 'A'}, { name: 'B'} ]
  $scope.showFoo1 = false
  $scope.showFoo1List = function() { 
    $scope.showFoo1 = true 
  }
  $scope.func1 = function(index) { 
    console.log($scope.foo1[index]) 
    $scope.showFoo1 = false
  }
  
  // Foo2
  $scope.foo2 = [ { name: 'Y'}, { name: 'Z'} ]
  $scope.showFoo2 = false
  $scope.showFoo2List = function() { 
    $scope.showFoo2 = true 
  }
  $scope.func2 = function(index) { 
    console.log($scope.foo2[index]) 
    $scope.showFoo2 = false
  }
})

指令

我的-directive.js

angular.module('app')
.directive('myDirective',
  function(){
    return {
      restrict: 'AE',
      scope: {
        lists: '=',
        showFoo: '&',
        show: '=',
        func: '&' // pass the function(param) to here
      },
      templateUrl: 'my-directive.html',
    }
  }
)

我的-directive.html

<button ng-click="showFoo()">
  click me
</button>
<div ng-repeat="item in lists" 
     ng-show="show"
     ng-click="func($index)"> <!-- here it refers to func1(index) or func2(index) in parent controller -->
  {{item.name}}
</div>

万分感谢!

回答这个问题的关键是映射属性的方式。如果要传递引用,则必须在指令范围内使用“=”字符,并将函数传递给指令而不调用它。如果您使用 '&' 字符,Angular 会创建一个函数来包装您作为属性传递的表达式。

试试这个:

angular.module('app')
.directive('myDirective',
  function(){
    return {
      restrict: 'AE',
      scope: {
        lists: '=',
        showFoo: '=',
        show: '=',
        func: '=' // pass the function(param) to here
      },
      templateUrl: 'my-directive.html',
    }
  }
)

<my-directive lists="foo2" 
          item-click="showFoo2List()" 
          show-foo="showFoo2" 
          func="func2">  <!-- this one -->
</my-directive>

查看此处了解更多信息。对你以后的发展很有帮助。

AngularDirectives