简体   繁体   English

指令AngularJS的呼叫控制器功能

[英]Call Controllers function from Directive AngularJS

How to call controllers method in directive in below code: 如何在以下代码的指令中调用controllers方法:

app.controller("main",['$scope','$http',function($scope,$http){
$scope.SelectCollege = function (){
     //Code to search college
}
}]);

Directive 指示

    angular.module('angucomplete', [] )
        .directive('angucomplete', function ($parse, $http, $sce, $timeout) {

   link: function($scope, elem, attrs) {
                $("#search_value").autocomplete({
                        source: $scope.localData,
                        select: function( event, ui ) {

                            //How to call controller's method here

                        }
                    });
            }
 });

Assuming the directive is placed inside the controller scope (element with ng-controller ) 假设指令位于控制器范围内(与ng-controller一起使用)

select: function( event, ui ) {

   //How to call controller's method here
   //Answer: as shown below
   $scope.SelectCollege();

}

you can include you controller with directive property 您可以将控制器包含指令属性

The controller option takes a string or a function. 控制器选项采用字符串或函数。 When set to a string, the name of the string is used to look up a controller constructor function registered elsewhere in our application: 当设置为字符串时,该字符串的名称用于查找在应用程序其他位置注册的控制器构造函数:

angular.module('myApp', [])
   .directive('myDirective', function() {
   restrict: 'A', // always required
   controller: 'SomeController',
   link: function(scope, element, attrs, SomeController) {
         SomeController.doSomething(scope);
  },
})
   // elsewhere in our application
   // either in the same file or another
   // one included by our index.html
angular.module('myApp')
  .controller('SomeController', function($scope, $element, $attrs, $transclude) {
      // controller logic goes here
})

You can pass your controller's method to the directive's scope like so: 您可以将控制器的方法传递给指令的范围,如下所示:

<autocomplete on-select="SelectCollege()"></autocomplete>

And in your directive define your scope 并在您的指令中定义您的范围

scope: {
    onSelect: "&onSelect"
}

Then within your directive you would just call it as: 然后在您的指令中,您只需将其称为:

 $scope.onSelect()

Alternatively you can just use $scope.SelectCollege() inside your directive if your directive is placed within controllers scope and your directive does not declare its own scope but inherits from controllers scope. 另外,如果您的指令位于控制器作用域内, 并且您的指令未声明其自身作用域而是从控制器作用域继承,则可以仅在指令内使用$scope.SelectCollege() Example: 例:

<div ng-controller="main">
    <autocomplete></autocomplete>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM