簡體   English   中英

控制器中的Angular.js調用指令函數

[英]Angular.js call directive function in controller

我想調用指令中定義的函數,與這個stackoverflow問題恰好相反

我嘗試了這個,但是沒有用。

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.someDirectiveFn = function(arg) {
                 return "in directive";
            };
        },
    }
});

function MyCtrl($scope) {
    alert($scope.someDirectiveFn());
}

那可能嗎? 我怎么能得到它? 這是不好的做法嗎?

編輯

我這樣子:

.controller('MyCtrl', function($scope) {
    alert($scope.func());
})

.directive('myDirective', function() {
    return {
      controller: function($scope, $element){
        $scope.func = function() {
          return "text";
         };
      }
    }
});

您可以使用事件系統來實現。

首先,使用您的參數在您的范圍內發出自定義事件。 其次,使用angular $ on方法監聽指令中的作用域。

app.controller('MyCtrl', function($scope) {
  $scope.invokeDirectiveMethod = function() {
    $scope.$emit('invokeMyDirectiveMethod', 'myParameter');
  };
})

.directive('myDirective', function() {
  return {
    link: function(scope, element, attrs) {
      var someDirectiveFn = function(event, arg) {
        alert(arg + " in directive");
      };

      scope.$on('invokeMyDirectiveMethod', someDirectiveFn);
    },
  }
});

這是一個正在工作的朋克

UPDATE

根據您的更新,事件通信不適合您的問題。

如何通過兩種方式將對象傳遞給指令並在該對象中定義someDirectiveFn呢? 這樣,您可以傳遞參數並從中返回值。

app.controller('MyCtrl', function($scope) {
  $scope.shareObject = {};

  $scope.invokeDirectiveMethod = function() {
    if (angular.isFunction($scope.shareObject.someDirectiveFn)) {
      $scope.message = $scope.shareObject.someDirectiveFn('from controller'); 
    }
  };
})

.directive('myDirective', function() {
  return {
    scope: {
      'shareObject': '='
    },
    link: function(scope, element, attrs) {
      scope.shareObject.someDirectiveFn = function(arg) {
        return arg + ' from parameter';
      };
    },
  }
});

更新了插件

您沒有發布html代碼,所以我假設您的自定義指令在IN MyCtrl 由於執行功能時該方法不起作用。

控制器功能始終在鏈接功能之前執行。

是一篇有關差異的很酷的文章。

因此,如果希望控制器能夠在指令中調用函數,則可以廣播事件(如halilb的回答),也可以使指令監聽特定的作用域值,如下所示:

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$watch("message", function() { console.log(message); });
        },
    }
});

function MyCtrl($scope) {
    $scope.message = "Hello Directive";
}

我猜您想擁有一個在指令和控制器之間共享的功能,可以這么說嗎?

如果是這樣的話,如何創建服務並將服務注入指令和ctrl中。 這樣,您只需創建一次即可。

  app.service('sharedFucntionService', function() {
     return {
        someFn : function (arg) {
             alert(arg + " in directive")  
        }
    }
 });

將服務注入指令

 app.directive('myDirective',function( sharedFucntionService){
  return {
        link: function (scope, element, attrs) {
            // do something with sharedFucntionService
        }
    }

});

將服務以及功能MyCtrl($ scope,sharedFucntionService){......}注入控制器。

暫無
暫無

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

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