从另一个控制器更新$ scope信息

时间:2016-08-15 08:31:20

标签: angularjs

如何让testservice工厂返回发布请求的结果?或者让应用,工厂更新$scope内的一些overallcontroller详细信息?

如何从其他控制器更新overallcontroller内的信息?

app.factory('testservice', ['$http', 'auth', function($http, auth) {

var o = {
    posts : []
};

o.test = function() {
  return $http.post('/poster', null, {
    headers: {Authorization: 'Bearer '+auth.getToken()}
  }).success(function(data){
   console.log(Data);


  });
};  



return o;

}]);

    app.controller('overallController', ['$scope', 'posts', 'testservice', 'auth','$interval',
function($scope, posts, testservice,  auth, $interval) {

    $scope.data = {cash:"12879999",location:"test2",gang:"None","username":"test",
    xp: 1290,
    health: 100,
    wanted: 30,
    energy: 90};


    var databackground = function() {
          console.log("logging...");
          var t = testservice.test;
          console.log(t);


    }

    databackground();
             $interval(databackground, 30000);




}]);

示例html

   <div class="main" ng-controller="overallController">
   <section class="sides left" style="background:blue; height:100px;">
    <ul>
      <li ng-hide="isLoggedIn()"><a href="/#/login">Logg inn</a></li>

    </ul>
   </section>
<div ng-controller"othercontroller">
 // call made from some code here
</div>
</div>

2 个答案:

答案 0 :(得分:0)

您将从您的服务中退回承诺,您将倾听此消息以获取并获取您的数据。

使用$rootScope是一种苛刻的方法,应该作为最后的手段。服务和活动更可取。

var databackground = function() {
  console.log("logging...");
  testservice.test()
    .then(function (res) {
        console.log(res.data); //Here is your data
    });
}

编辑:您的服务也应略有变化。首先,不推荐使用.success.error。请改用.then.catch

如果您希望仅从服务中返回数据,请执行以下操作:

o.test = function() {
  return $http.post('/poster', null, {
    headers: {
      Authorization: 'Bearer ' + auth.getToken()
    }
  });
};

但是,如果您想要转换服务中的数据,您可以确保退货或控制器无法获得任何内容:

o.test = function() {
  return $http.post('/poster', null, {
    headers: {
      Authorization: 'Bearer ' + auth.getToken()
    }
  })
  .then(function (res) {
    res.data.test = 'lol';

    return res;
  })
};

答案 1 :(得分:-1)

尝试引用$ rootScope而不是$ scope。

这将允许控制器和工厂相互交互。