使指令函数在父范围内可访问而无需事件

Make directive function accessible in parent scope without events

我有一个 指令 和一个独立的 scope 并且想调用它的函数来更新来自父 的数据controller 不使用 events.

var myApp = angular.module('MyApp',[]);

myApp.directive('myDirective', function() {

  return {
    scope: {},
    link: function(scope) {
      scope.update = function() {
        alert('Directive updated!');
      }
    }
  }
  
});

function MyCtrl($scope) {
  
  $scope.updateDirective = function() {
    // make me call update() function in directive
  }
    
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp" ng-controller="MyCtrl">
  <button ng-click="updateDirective()">Update!</button>
  
  <span my-directive></span>
</div>

您可以应用此解决方案。

通过这种方式,您可以通过两种方式绑定传递变量:

  • my-directive="myFunction" 在 html
  • 和指令中的myFunction: '=myDirective'

然后在指令中赋值函数:

    scope.myFunction = function () {
        alert('Directive updated!');
    }

通过这种方式,您可以使用指令中定义的函数。

var myApp = angular.module('MyApp', []);

myApp.directive('myDirective', function () {

    return {
        scope: {
            myFunction: '=myDirective'
        },
        link: function (scope) {

            scope.myFunction = function () {
                alert('Directive updated!');
            }

        }
    }

});

function MyCtrl($scope) {
    $scope.myFunction = {};
    $scope.updateDirective = function () {
        console.log( $scope.myFunction );
        $scope.myFunction();
        // make me call update() function in directive
    }

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
    <button ng-click="updateDirective()">Update!</button> <span my-directive="myFunction"></span>

</div>

您可以通过引入一个新指令来解决此问题,该新指令由您的独立指令 required 定义。方便的是,您可以将控制器分配给这个新指令。

一旦需要,您就可以 'register' 将 'parent' 指令的独立指令作为函数的目标。在下面的代码片段中,我只提供了一种添加 1 指令的方法,但您可以轻松地将其扩展为子指令数组。这种设置的一个很好的例子是选项卡,其中每个 tab 都是通用 tabs 指令的子指令。

angular.module("MyApp", []);

angular.module('MyApp').directive("myParentDirective", function(){
return {
    controller: function ($scope) {
        var childUpdate;
        this.registerChild = function(_childUpdate_){
            childUpdate = _childUpdate_;
        };      
        
        $scope.updateDirective = function() {
            childUpdate();
        };

    }
};
});
angular.module('MyApp').directive('myDirective', function() {
return {
    require: '^myParentDirective',
    scope: {},
    link: function(scope, element, attrs, myParentController) {
        myParentController.registerChild(update);
        
        function update() {
            alert('Directive updated!');
        }
    }
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">
    <div my-parent-directive>
        <button ng-click="updateDirective()">Update!</button>
        <span my-directive></span>
    </div>
</div>