繁体   English   中英

指令AngularJS的呼叫控制器功能

[英]Call Controllers function from Directive AngularJS

如何在以下代码的指令中调用controllers方法:

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

指示

    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

                        }
                    });
            }
 });

假设指令位于控制器范围内(与ng-controller一起使用)

select: function( event, ui ) {

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

}

您可以将控制器包含指令属性

控制器选项采用字符串或函数。 当设置为字符串时,该字符串的名称用于查找在应用程序其他位置注册的控制器构造函数:

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
})

您可以将控制器的方法传递给指令的范围,如下所示:

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

并在您的指令中定义您的范围

scope: {
    onSelect: "&onSelect"
}

然后在您的指令中,您只需将其称为:

 $scope.onSelect()

另外,如果您的指令位于控制器作用域内, 并且您的指令未声明其自身作用域而是从控制器作用域继承,则可以仅在指令内使用$scope.SelectCollege() 例:

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

暂无
暂无

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

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