javascript - 将js文件中的指令函数加载到另一个 Controller js文件中

标签 javascript angularjs

我有一个主 js 文件, Controller 中有 watch -

(function () {
    'use strict';

    angular
        .module('mainmodule')
        .controller('file1Ctrl', file1Ctrl);

    
    file1Ctrl.$inject = ['$scope','data'];
    function VendorDetailCtrl($scope,data){
    var vd = this;
    vd.data.id = data.id;
    activate();
    
    function activate() {
      $scope.$watch("vd.data.id", function (newValue, oldValue) {

                        if (newValue !== oldValue) {
                            callmainfunction();
                        }

                    });
    }
    })();
    

然后我在另一个 js 文件中有另一个指令 -

(function () {
    'use strict';

    angular
        .module('mainmodule')
        .directive('file2', file2)

    function file2() {
        var directive = {
            restrict: 'E',
            templateUrl: 'file2.html',
            scope: {
                data: '=',
            },
            
            controller: ['$scope',file2Ctrl],
            controllerAs: 'vm',
            bindToController: true
        }

        return directive;
        function file2Ctrl($scope, file2Ctrl) {
            var vm = this;
            activate();
            
            function activate(){
            neededfunc();
            }
            
            function neededfunc(){
            //do something
            }
      })();

我需要在第一个js文件中调用 watch 中的neededfunc()。我什至尝试在指令中添加监视,但它仅在页面重新加载时触发,并且我需要它在单击按钮 Submit() 后运行。当我点击按钮 Submit() 时, watch 就会被触发。所以我需要知道如何在 watch 中使用该函数,或者当 id 值更改时是否有其他方法可以调用该函数。

最佳答案

向 $scope.$root 添加函数有帮助。以下是代码 -

// Declare the function

$scope.$root.neededFunction = function(){
//Do Something here
}


//Call the function

$scope.$root.neededFunction();

关于javascript - 将js文件中的指令函数加载到另一个 Controller js文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307564/

相关文章:

css - AngularJS View 渲染问题

javascript - d3.js:访问向下嵌套 2 级的数据

javascript - 使用变量 self 与 this 之间的区别

javascript - 仅对一个元素使用each-ready 函数?

jquery - 在我的链接函数中注册的事件监听器未被触发

javascript - 使用 UI-Router 防止后退按钮的状态更改

javascript - Focusin 和 focusout 方法在 Firefox 中不起作用

javascript - 如何从POST请求中获取数据

javascript - 使用 Javascript 中的 regex 或 indexOf 更改字符串中的特定字符(转义字符)

javascript - Angularjs 的 HTML 模板语言