簡體   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