Angular1.0 在Directive中调用Controller的方法

Controller中定义了$scope.method = function(){}

Directive中需要引入$scope

http://stackoverflow.com/questions/23636727/how-to-call-controller-function-from-directive

JS:

angular.module('myApp', [])
.controller('MyController', function($scope){
  $scope.showAlert = function(value){
    alert('Called from directive: ' + value);
  };
})
.directive('myDirective', function(){
  return {
    restrict: 'E',
    scope: {
      alert: '&'
    },
    controller: function($scope){
      $scope.value = 'directive scope value';
    },
    template: '<button ng-click="alert({message: value})">Alert</button>'
  }
});
HTML:

<body ng-app="myApp" ng-controller="MyController">
  <my-directive alert="showAlert(message)"></my-directive>
</body>

My recommendation is to use $emit instead of calling a method of the controller directly in your directive.

Directives should be always independent components, if inside the directive there is a call to a method from a controller(outside the directive) this will create a dependency between my directive and the controller and of course this will force one not being able to exist without the other.

If I would have to apply a design principle to a directive it will be the S in SOLID, Single responsibility principle. Directives should be able to encapsulate and work independently.

On my controller the event is captured using $on like:

$scope.$on("ValueChanged", function(event, ars){
   ... //your event has been triggered.    
});

或者

var directive= function ( $sessionStorage, $localStorage) {
            function work(scope, element, attrs, formCtrl) {
                var watchPromise = attrs.createClaimForm || null;
                element.bind('keypress', function (event) {
//此处scope就是$scope 
                        scope.addBlankRowData();
                    }
                });

 return {
                require: "form",
                restrict: "A",
                link: work
            }
 };

Controller中this.method = function(){}是获取不到的, 必须$scope

原文地址:https://www.cnblogs.com/haimingpro/p/6677842.html