javascript - 从 Directive AngularJS 调用 Controller 函数

标签 javascript angularjs jquery-ui

如何在下面的代码中调用指令中的 Controller 方法:

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

                        }
                    });
            }
 });

最佳答案

您可以将 Controller 包含在指令属性中

Controller 选项采用字符串或函数。当设置为字符串时,字符串的名称为 用于查找在我们的应用程序中其他地方注册的 Controller 构造函数:

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

关于javascript - 从 Directive AngularJS 调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25176207/

相关文章:

javascript - 使用 JQuery 代替 CSS 的幻灯片动画

javascript - 如何在点击图片时打开另存为..对话框?

javascript - 如果文件更改,如何自动增加 javascript 版本?

javascript - 按钮 ng-click 和 ng-keyup 的 IE10 事件处理

css - Jquery UI 无法拖动选择

javascript - 非等于数组同时更改值javascript

javascript - window.XXX = require(YYY) VS const {XXX} = require(YYY) : which to use?

AngularJS - 两个同级 DOM 元素上的一个 Controller

javascript - Kendo UI 无法过滤网格表

javascript - 使用 javascript/jquery 显示 iframe