如何在父作用域中使用参数执行函数?

时间:2014-10-04 20:18:40

标签: angularjs data-binding directive

有时需要从具有隔离范围的指令调用父作用域中定义的函数。要使用外部作用域中定义的函数,通常使用&。但它不允许在函数中发送参数。我只能使用=指令数据绑定。请考虑我在plnkr上的示例,并告诉我是否可以使用&并将数据放入回调函数中。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  function updateNumber(number){
    $scope.randomNumber = number;
  }
  $scope.randomNumber = 0;
  $scope.updateNumber = updateNumber;
});

app.directive('randomGenerator', function(){
  return {
    scope:{
      onUpdate:'='
      ^^^^^^^^^^^^
      // I want to use '&', but cannot call onUpdate(something)
    },
    restrict: 'E',
    replace: true,
    template: '<button ng-click="update()">Random</button>',
    link: function(scope,elem,attrs){
        scope.update = function(){
          var random = Math.random();
          scope.onUpdate(random);
        };
    }
  };
});

HTML

  <body ng-controller="MainCtrl">
    <h1>Random numbers generator </h1>
    <random-generator on-update="updateNumber"></random-generator>
    {{randomNumber}}
  </body>

1 个答案:

答案 0 :(得分:1)

请参阅此处http://plnkr.co/edit/y0s43VQwpDb6Jyx3HzX9?p=preview

更多信息https://groups.google.com/forum/#!topic/angular/3CHdR_THaNw

<强> HTML:

      <body ng-controller="MainCtrl">
        <h1>Random numbers generator </h1>
         <!-- Add name oF parametr in your directive [NUMBER] -->
        <random-generator on-update="updateNumber(number)"></random-generator>
        {{randomNumber}}
      </body>

<强>指令:

app.directive('randomGenerator', function() {
  return {
    scope: {
      onUpdate: '&'
    },
    restrict: 'E',
    replace: true,
    template: '<button ng-click="update()">Random</button>',
    link: function(scope, elem, attrs) {
      scope.update = function() {
        var random = Math.random();

//passing parameter should be named and the name needs to match that on in HTML [NUMBER]
        scope.onUpdate({
          number: random
        });
      };
    }
  };
});