javascript - Controller 和指令之间的 AngularJS 通信

标签 javascript web angularjs

如何从 Controller 获取一些数据并在指令中使用它不是问题。 但是当我需要从指令获取数据并在我的 Controller 中使用它时,我会遇到这种情况。

例如:

我的 Controller :

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...");
        }

};
})

如何在我的 Controller 中使用指令中的变量或/和方法?

最佳答案

完成此操作的最简单方法是让您的 Controller 和指令都从服务中获取 importantValuecreate()

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

现在您可以将 sharedData 注入(inject)到您的指令和 Controller 中,并从任一位置访问 importantValuecreate()

关于javascript - Controller 和指令之间的 AngularJS 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483336/

相关文章:

javascript - 当输入范围达到一定值时运行 JS 脚本

JavaScript 重复函数

jsf - 如何将每个文件夹中的 index.html 更改为/当我们在浏览器上访问它时

javascript - Angular 服务 - 多个查询和求和

javascript - leaflet和leaflet draw vue leaflet.draw.js的问题?20d6 :8 Uncaught TypeError: Cannot read properties of undefined (reading 'length' )

带有对象键的 JavaScript setter 和 getter

angularjs - 移动应用程序如何在本地存储消息?

angularjs:是否可以从 self 指令编译函数访问指令名称?

javascript - 错误: $injector:unpr Unknown Provider in angularjs with gulp-uglify

javascript - Gulp watch 响应不正确