簡體   English   中英

如何從Angular的控制器中調用指令的函數

[英]How to call a directive's function from the controller on Angular

我有一個控制個性化多選的指令。 有時我想從主控制器中清除所有多選。 我具有填充“雙向filter ”雙向變量的multiselect值,並且能夠從其中刪除內容,但是這樣做時,我還必須更改某些樣式和其他內容。 換句話說:我必須從屬於控制器的按鈕調用屬於指令的方法。 使用這種數據結構甚至可能嗎?

(順便說一句,我發現了其他問題和示例,但它們的指令沒有自己的范圍。)

function MultiselectDirective($http, $sce) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'temp.html',
        scope: {
            filter: "=",
            name: "@",
            url: "@"
        },
        link: function(scope, element, attrs){
           //do stuff
           scope.function_i_need_to_call = function(){
              //updates directtive template styles
           }
        }
    }
}

最佳解決方案和角度使用event

jsfiddle上的實時示例。

 angular.module('ExampleApp', []) .controller('ExampleOneController', function($scope) { $scope.raise = function(val){ $scope.$broadcast('raise.event',val); }; }) .controller('ExampleTwoController', function($scope) { $scope.raise = function(val){ $scope.$broadcast('raise.event',val); }; }) .directive('simple', function() { return { restrict: 'A', scope: { }, link: function(scope) { scope.$on('raise.event',function(event,val){ console.log('i`m from '+val); }); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="ExampleApp"> <div ng-controller="ExampleOneController"> <h3> ExampleOneController </h3> <form name="ExampleForm" id="ExampleForm"> <button ng-click="raise(1)" simple> Raise 1 </button> </form> </div> <div ng-controller="ExampleTwoController"> <h3> ExampleTwoController </h3> <form name="ExampleForm" id="ExampleForm"> <button ng-click="raise(2)" simple> Raise 2 </button> </form> </div> </body> 

我認為從控制器鏈接到指令的更好解決方案是:

// in directive

   return {
      scope: {
                controller: "=",         
             },
      controller: function($scope){
         $scope.mode = $scope.controller.mode;
         $scope.controller.function_i_need_to_call = function(){}
         $scope.controller.currentState = state;
      }
   }

// in controller
function testCtrl($scope){

     // config directive
     $scope.multiselectDirectiveController = {
           mode: 'test',
     };

     // call directive methods
     $scope.multiselectDirectiveController.function_i_need_to_call();

     // get directive property
     $scope.multiselectDirectiveController.currentState;
}

// in template
<Multiselect-directive controller="multiselectDirectiveController"></Multiselect-directive>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM