Call function on directive parent scope with directive scope argument

99封情书 提交于 2019-11-29 22:57:34

Update

You can also use & to bind the function of the root scope (that is actually the purpose of &).

To do so the directive needs to be slightly changed:

app.directive('toggle', function(){
  return {
    restrict: 'A',
    template: '<a ng-click="f()">Click Me</a>',
    replace: true,
    scope: {
      toggle: '&'
    },
    controller: function($scope) {
      $scope.toggleValue = false;
      $scope.f = function() {
        $scope.toggleValue = !$scope.toggleValue;
        $scope.toggle({message: $scope.toggleValue});
      };
    }
  };
});

You can use like this:

<div toggle="parentToggle(message)"></div>

Plunk


You could bind the function using =. In addition ensure the property name in your scope and tag are matching (AngularJS translates CamelCase to dash notation).

Before:

scope: {
  OnToggle: '&'
}

After:

scope: {
  onToggle: '='
}

Furthermore don't use on-toggle="parentToggle({value: toggleValue})" in your main template. You do not want to call the function but just passing a pointer of the function to the directive.

Plunk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!