如何将变量值从一个控制器传递到另一个控制器?

时间:2016-01-12 18:19:13

标签: javascript angularjs

我有两个不同的控制器,我试图传递变量值来做一些动作,我使用$broadcast angularJS事件,但它无法正常工作。有没有其他解决方案可以完成这项任务?

据我所知,关于控制器之间的变量已经有问题,但我想知道其他可能的灵魂。

ctrl1.js

$scope.viewAssessmentFrmCycle = function(assessmentId) {
      $scope.$broadcast('viewAssessment',assessmentId);
    }

ctrl2.js

 $scope.$on('viewAssessment',function(s,assessmentId){
                      console.log(assessmentId);
                      $location.path('/rcsa/editAssessmentFromCycle/'+assessmentId+);

                    });

3 个答案:

答案 0 :(得分:3)

使用服务。

angular.module('myApp', [])
    .service('ShareThis', function () {
        var value = 'myValue';

        return {
            getValue: function () {
                return value;
            },
            setValue: function(newValue) {
                value = newValue;
            }
        };
    });

然后,您可以通过设置或获取...

在每个控制器中访问它

例如:

myApp.controller('Ctrl1', function($scope, ShareThis) {
  $scope.value = ShareThis.getValue();
});

myApp.controller('Ctrl2', function ($scope, ShareThis) {
 $scope.setVal = function(val) {
   ShareThis.setValue(val); 
 }
}

答案 1 :(得分:0)

您可以创建工厂来保存数据。

厂:

angular.module('myModule').factory('commonData', function(){
  var commonValue = {};
  return {
    getData : function(){ return commonValue },
    setData : function(newData) { commonValue = newData }
  }
});

然后将此工厂注入您的控制器并使用set和get函数来操作数据。

答案 2 :(得分:0)

使用工厂来保存您的数据..

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

// create a mediator factory which will persist the data
app.factory("MediatorFactory", function() {
    return {
        obj: {
            value: ""
        }
    };
});

app.controller("FirstCtrl", ["MediatorFactory", function(mediator) {
    this.variable1 = mediator.obj;
}]);

app.controller("SecondCtrl", ["MediatorFactory", function(mediator) {
    this.variable2 = mediator.obj; // this.variable2 = this.variable1 in the controller1
}]);
相关问题