问题描述:

I have a directive, here is the code :

.directive('map', function() {

return {

restrict: 'E',

replace: true,

template: '<div></div>',

link: function($scope, element, attrs) {

var center = new google.maps.LatLng(50.1, 14.4);

$scope.map_options = {

zoom: 14,

center: center,

mapTypeId: google.maps.MapTypeId.ROADMAP

};

// create map

var map = new google.maps.Map(document.getElementById(attrs.id), $scope.map_options);

var dirService= new google.maps.DirectionsService();

var dirRenderer= new google.maps.DirectionsRenderer()

var showDirections = function(dirResult, dirStatus) {

if (dirStatus != google.maps.DirectionsStatus.OK) {

alert('Directions failed: ' + dirStatus);

return;

}

// Show directions

dirRenderer.setMap(map);

//$scope.dirRenderer.setPanel(Demo.dirContainer);

dirRenderer.setDirections(dirResult);

};

// Watch

var updateMap = function(){

dirService.route($scope.dirRequest, showDirections);

};

$scope.$watch('dirRequest.origin', updateMap);

google.maps.event.addListener(map, 'zoom_changed', function() {

$scope.map_options.zoom = map.getZoom();

});

dirService.route($scope.dirRequest, showDirections);

}

}

})

I would like to call updateMap() on a user action. The action button is not on the directive.

What is the best way to call updateMap() from a controller?

网友答案:

To be honest, I was not really convinced with any of the answers in this thread. So, here's are my solutions:

Directive Handler(Manager) Approach

This method is agnostic to whether the directive's $scope is a shared one or isolated one

A factory to register the directive instances

angular.module('myModule').factory('MyDirectiveHandler', function() {
    var instance_map = {};
    var service = {
        registerDirective: registerDirective,
        getDirective: getDirective,
        deregisterDirective: deregisterDirective
    };

    return service;

    function registerDirective(name, ctrl) {
        instance_map[name] = ctrl;
    }

    function getDirective(name) {
        return instance_map[name];
    }

    function deregisterDirective(name) {
        instance_map[name] = null;
    }
});

The directive code, I usually put all the logic that doesn't deal with DOM inside directive controller. And registering the controller instance inside our handler

angular.module('myModule').directive('myDirective', function(MyDirectiveHandler) {
    var directive = {
        link: link,
        controller: controller
    };

    return directive;

    function link() {
        //link fn code
    }

    function controller($scope, $attrs) {
        var name = $attrs.name;

        this.updateMap = function() {
            //some code
        };

        MyDirectiveHandler.registerDirective(name, this);

        $scope.$on('destroy', function() {
            MyDirectiveHandler.deregisterDirective(name);
        });
    }
})

template code

<div my-directive name="foo"></div>

Access the controller instance using the factory & run the publicly exposed methods

angular.module('myModule').controller('MyController', function(MyDirectiveHandler, $scope) {
    $scope.someFn = function() {
        MyDirectiveHandler.get('foo').updateMap();
    };
});

Angular's approach

Taking a leaf out of angular's book on how they deal with

<form name="my_form"></form>

using $parse and registering controller on $parent scope. This technique doesn't work on isolated $scope directives.

angular.module('myModule').directive('myDirective', function($parse) {
    var directive = {
        link: link,
        controller: controller,
        scope: true
    };

    return directive;

    function link() {
        //link fn code
    }

    function controller($scope, $attrs) {
        $parse($attrs.name).assign($scope.$parent, this);

        this.updateMap = function() {
            //some code
        };
    }
})

Access it inside controller using $scope.foo

angular.module('myModule').controller('MyController', function($scope) {
    $scope.someFn = function() {
        $scope.foo.updateMap();
    };
});
网友答案:

You can specify a DOM attribute that can be used to allow the directive to define a function on the parent scope. The parent scope can then call this method like any other. Here's a plunker. And below is the relevant code.

clearfn is an attribute on the directive element into which the parent scope can pass a scope property which the directive can then set to a function that accomplish's the desired behavior.

<!DOCTYPE html>
<html ng-app="myapp">
  <head>
    <script data-require="[email protected]*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <style>
      my-box{
        display:block;
        border:solid 1px #aaa;
        min-width:50px;
        min-height:50px;
        padding:.5em;
        margin:1em;
        outline:0px;
        box-shadow:inset 0px 0px .4em #aaa;
      }
    </style>
  </head>
  <body ng-controller="mycontroller">
    <h1>Call method on directive</h1>
    <button ng-click="clear()">Clear</button>
    <my-box clearfn="clear" contentEditable=true></my-box>
    <script>
      var app = angular.module('myapp', []);
      app.controller('mycontroller', function($scope){
      });
      app.directive('myBox', function(){
        return {
          restrict: 'E',
          scope: {
            clearFn: '=clearfn'
          },
          template: '',
          link: function(scope, element, attrs){
            element.html('Hello World!');
            scope.clearFn = function(){
              element.html('');
            };
          }
        }
      });
    </script>
  </body>
</html>
网友答案:

Just use scope.$parent to associate function called to directive function

angular.module('myApp', [])
.controller('MyCtrl',['$scope',function($scope) {

}])
.directive('mydirective',function(){
 function link(scope, el, attr){
   //use scope.$parent to associate the function called to directive function
   scope.$parent.myfunction = function directivefunction(parameter){
     //do something
}
}
return {
        link: link,
        restrict: 'E'   
      };
});

in HTML

<div ng-controller="MyCtrl">
    <mydirective></mydirective>
    <button ng-click="myfunction(parameter)">call()</button>
</div>
网友答案:

You can tell the method name to directive to define which you want to call from controller but without isolate scope,

angular.module("app", [])
  .directive("palyer", [
    function() {
      return {
        restrict: "A",
        template:'<div class="player"><span ng-bind="text"></span></div>',
        link: function($scope, element, attr) {
          if (attr.toPlay) {
            $scope[attr.toPlay] = function(name) {
              $scope.text = name + " playing...";
            }
          }
        }
      };
    }
  ])
  .controller("playerController", ["$scope",
    function($scope) {
      $scope.clickPlay = function() {
        $scope.play('AR Song');
      };
    }
  ]);
.player{
  border:1px solid;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="playerController">
    <p>Click play button to play
      <p>
        <p palyer="" to-play="play"></p>
        <button ng-click="clickPlay()">Play</button>

  </div>
</div>
网友答案:

Maybe this is not the best choice, but you can do angular.element("#element").isolateScope() or $("#element").isolateScope() to access the scope and/or the controller of your directive.

网友答案:

How to get a directive's controller in a page controller:

  1. write a custom directive to get the reference to the directive controller from the DOM element:

    angular.module('myApp')
        .directive('controller', controller);
    
    controller.$inject = ['$parse'];
    
    function controller($parse) {
        var directive = {
            restrict: 'A',
            link: linkFunction
        };
        return directive;
    
        function linkFunction(scope, el, attrs) {
            var directiveName = attrs.$normalize(el.prop("tagName").toLowerCase());
            var directiveController = el.controller(directiveName);
    
            var model = $parse(attrs.controller);
            model.assign(scope, directiveController);
        }
    }
    
  2. use it in the page controller's html:

    <my-directive controller="vm.myDirectiveController"></my-directive>
    
  3. Use the directive controller in the page controller:

    vm.myDirectiveController.callSomeMethod();
    

Note: the given solution works only for element directives' controllers (tag name is used to get the name of the wanted directive).

相关阅读:
Top