简体   繁体   中英

Call Controllers function from Directive AngularJS

How to call controllers method in directive in below code:

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 )

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. Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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