如何将数据从一个控制器传递到AngularJs中的其他控制器

时间:2016-07-07 13:05:05

标签: javascript html angularjs

我已经看到有关堆栈溢出的各种帖子,我尝试流动,但是我在创建服务时遇到的一些错误是我的代码请帮助我找出我做错的地方



angular
.module('yolomd', ['ngSanitize']);
app.factory('myplacementdata', function () {
    var mydata = {

      placementdata = [],
      getplacementdataValue:function () {
         return mydata.placementdata; 
      },
      setplacementdataValue: function (data) {
        mydata.placementdata = data;
      }
    }
    return mydata;
});

app.controller('PriorityPlacement',['$scope', '$rootScope','myplacementdata', function($scope, $rootScope,myplacementdata){  
  var response.Data=[{city_name: "Toronto", city_placement_charge: "1799"}, yolomd_verify: "50"];
    myplacementdata.setplacementdataValue=response.Data;
    console.log(myplacementdata.getplacementdataValue);
    //window.location = site_url + 'Overview'
   }]);
app.controller('Overview',['$scope', '$rootScope','$stateParams','myplacementdata', function($scope, $rootScope,myplacementdata){
    console.log(myplacementdata.getplacementdataValue);
   }])

<html lang="en" ng-app="yolomd">
<head>
  <script src="http://205.134.251.196/~examin8/CI/yoloMD/assets/front/js/vendor/angular.min.js"></script>
  </head>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

首先尝试更改

myplacementdata.setplacementdataValue=response.Data;

 myplacementdata.setplacementdataValue(response.Data);

你从哪里获得response.Data来自?

尝试使用工厂代替。像这样。

app.factory('myplacementdata', function () {
    var mydata = {

      placementdata = [],
      getplacementdataValue:function () {
         return mydata.placementdata; 
      },
      setplacementdataValue: function (data) {
        mydata.placementdata = data;
      }
    }
    return mydata;
});

答案 1 :(得分:1)

请注意:

setplacementdataValue()
getplacementdataValue()

这些是方法,而不是变量。

因此将它们用作:

setplacementdataValue([Your Array Input]);
console.log(getplacementdataValue());

注意括号。

同样在set方法中,使用不同的输入参数名称。

var app = angular.module("myApp", []);

app.controller('PriorityPlacement', ['myplacementdata',
  function(myplacementdata) {
    myplacementdata.setplacementdataValue([1, 2, 3]);
    console.log(myplacementdata.getplacementdataValue());
  }
]);

app.controller('Overview', ['myplacementdata',
  function(myplacementdata) {
    console.log(myplacementdata.getplacementdataValue());
  }
]);

app.service('myplacementdata', function() {
  var placementdata = [];
  this.getplacementdataValue = function() {
    return placementdata;
  }
  this.setplacementdataValue = function(myplacementdata) {
    placementdata = myplacementdata;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="PriorityPlacement">
  </div>
  <div ng-controller="Overview">
  </div>
</div>