簡體   English   中英

控制器和指令之間的AngularJS通信

[英]AngularJS communication between controller and directive

如何從控制器獲取一些數據並在指令中使用它沒有問題。 但是當我需要從指令中獲取數據並在我的控制器中使用它時,我會堆疊這種情況。

例如:

我的控制器:

function MyController($scope, $location, myDirective) {
    "use strict";

    // here i need use scope.importantValue and create() method from directive

}

我的指示:

        .directive("myDirective", function() {
"use strict";
return {
    restrict: 'A',
    template: '<div></div>',
    replace: true,
    scope: {
        data: '=',
    },
    link: function(scope, elm) {
        scope.importantValue = "value";

        function create() {
            console.log("Directive works...");
        }

};
})

如何在控制器中使用指令中的變量或/和方法?

實現此目的的最簡單方法是使控制器和指令從服務中獲取importantValuecreate()

angular.module(/* Your module */).service('sharedData', function () {
    return {
        importantValue: "value",
        create: function () {
            console.log("Directive works...");
        }
    };
});

現在,您可以將sharedData注入指令和控制器,並從任一位置訪問importantValuecreate()

暫無
暫無

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

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