使用&嵌套的AngularJS指令中的绑定

时间:2014-09-23 16:25:31

标签: javascript angularjs

我尝试通过另外两个指令绑定到由ng-change创建的元素,该指令通过隔离范围中的&绑定将其包装到控制器上的方法中,但我无法弄清楚如何让参数一直通过。这是一个显示问题的plunk

简而言之,我有一个像这样的HTML结构:

<body ng-app="ExampleApp">
  <div ng-controller="Controller">
    <button ng-click="doSomething('Called directly')">Call Function Directly</button>
    <br />
    <outer on-outer-model-changed="doSomething('Called from Outer in HTML')"></outer>
  </div>
</body>

控制器:

var app = angular.module('ExampleApp', []);
app.controller('Controller', ['$scope',
  function($scope) {
    $scope.doSomething = function(one, two, three) {
      console.log(arguments);
    };
  }
]);

outer指令:

app.directive('outer', function($compile) {
  return {
    restrict: 'E',
    scope: {
      outerModelChanged: '&onOuterModelChanged'
    },
    link: function(scope, element, attrs) {
      var innerElement = angular.element('<inner></inner>');
      innerElement.attr('on-inner-model-changed', 'outerModelChanged(\'Called from Outer\')');
      element.after(innerElement);
      $compile(innerElement)(scope);
      console.log(arguments);
    }
  }
});

inner指令创建的outer指令:

app.directive('inner', function() {
  return {
    scope: {
      innerModelChanged: '&onInnerModelChanged'
    },
    restrict: 'E',
    template: '<button ng-click="innerModelChanged(\'Called from Inner\')">Call from Inner</button>'
  }
});

我知道我获得了输出["Called from Outer in HTML"],因为它被硬编码到<outer>标记中。我不明白的是如何从inner指令一直传递参数。

1 个答案:

答案 0 :(得分:0)

我不确定我100%得到你想要完成的内容,但这就是你如何显示["Called from Inner"]消息。

更改html,以便on-outer-model-changed表达式不使用硬编码字符串。

  <body ng-app="ExampleApp">
    <div ng-controller="Controller">
      <button ng-click="doSomething('Called directly')">Call Function Directly</button>
      <br />
      <outer on-outer-model-changed="doSomething(outerParam)"></outer>
    </div>
  </body>

然后更改外部指令以使用参数调用outerModelChanged。并将outerParam设置为innerParam

app.directive('outer', function($compile) {
  return {
    restrict: 'E',
    scope: {
      outerModelChanged: '&onOuterModelChanged'
    },
    link: function(scope, element, attrs, controller) {
      var innerElement = angular.element('<inner></inner>');
      innerElement.attr('on-inner-model-changed', 'outerModelChanged({outerParam:innerParam})');
      element.after(innerElement);
      $compile(innerElement)(scope);
      console.log(arguments);
    }
  }
});

最后从内部指令调用innerModelChanged并将innerParam设置为您的消息。

app.directive('inner', function() {
  return {
    scope: {
      innerModelChanged: '&onInnerModelChanged'
    },
    restrict: 'E',
    template: '<button ng-click="innerModelChanged({innerParam:\'Called from Inner\'})">Call from Inner</button>'
  }
});

以上是代码的plunk