Angularjs如何从另一个控制器调用控制器的功能

时间:2014-02-18 23:37:33

标签: javascript angularjs

我正在尝试拆分一个大控制器。要走的路是通过工厂,但由于我要更改DOM,我应该通过控制器来完成。

然后,我想要实现的是从Cntrl1调用Cntrl2中定义的函数。 例子

HTML

<body ng-app="app">
<div ng-controller='Cntrl1'>
{{message}}
</div>
</body>

JS

var myModule = angular.module('app', []);

angular.module('app').controller('Cntrl1', 
['$scope', '$q', '$timeout', 'Share_scope', 
function ($scope, $q, $timeout, Share_scope) {
    Share_scope.process();
    $scope.message = 'started';
}]);

angular.module('app').controller('Cntrl2', 
['$scope', '$q', '$timeout', 'Share_scope', 
function ($scope, $q, $timeout, Share_scope) {
    Share_scope.x = function() {
           alert('done');
    }
}]);

angular.module('app').factory('Share_scope', 
['$window', '$q',
function($window, $q) {
    var x;
    return {
        process: function() {
            return x;
        },
    };
}]);

演示http://jsfiddle.net/T8rgv/7/

我期望将工厂的“var x”定义为Cntrl2的功能,然后当我从Cntrl1调用它时,通过工厂执行此功能。

那么,如何使这项工作?这种方法是否正确?或者我应该从工厂改变DOM?

干杯, 杰拉德

2 个答案:

答案 0 :(得分:1)

不知道Cntrl2与Cntrl1的关系在哪里,我会像这样使用emit或broadcast。请注意以往的经验,我不认为在同一页面中使用两个或更多不同的模块是个好主意。

var myModule = angular.module('app', []);

angular.module('app').controller('Cntrl1', 
['$scope', '$q', '$timeout', 'myFactory', 
function ($scope, $q, $timeout, myFactory) {
    $scope.$emit('messageEvt','started');
    myFactory.process().then(function() {
        $scope.$emit('messageEvt','ended');
    });
}]);

angular.module('app').controller('Cntrl2', 
['$scope', '$q', '$timeout', $rootScope, 
function ($scope, $q, $timeout, $rootScope) {
    $rootScope.$on('messageEvt',function(e,msg) {
        $scope.message = msg;
    }
}]);

angular.module('app').factory('myFactory', 
['$window', '$q','$timeout',
function($window, $q,$timeout) {
    var x;
    return {
        process: function() {
            var deferObj = $q.defer();
            $timeout(function() {
                deferObj.resolve(x);
            });
            return deferObj.promise;
        },
    };
}]);

答案 1 :(得分:0)

我认为更好的方法是让工厂维护模型,两个控制器在需要时更新它。

我将小提琴更新为http://jsfiddle.net/hh5Cy/2/

angular.module('app').factory('Share_scope', 
['$window', '$q',
function($window, $q) {
    var x;

    return {
        getProcess: function() {
            return x;
        },
        setProcess: function(value){
           x = value;
        }
    };
}]);

如果我错误地理解你,请告诉我。

相关问题