Call function on directive parent scope with directive scope argument

前端 未结 1 1581
旧巷少年郎
旧巷少年郎 2020-12-24 06:10

I am developing a directive which shows and hides it\'s contents based on a click event (ng-click) defined in it\'s template. On some views where the directive is used I\'d

相关标签:
1条回答
  • 2020-12-24 07:01

    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

    0 讨论(0)
提交回复
热议问题