码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-04-07 14:13:43      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:module   mis   always   form   style   span   this   .sh   int   

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

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

标签:module   mis   always   form   style   span   this   .sh   int   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!