2016-08-15 58 views
0

我怎樣才能使TestService的工廠從POST請求返回的結果?還是使應用程序,工廠更新overallcontroller內的一些細節$scope多數民衆贊成?

我怎樣才能更新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> 

回答

1

更改您的服務

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

而在你controlle R,做通話服務,並在承諾得到返回結果:

testservice.test().then(function(data) { 
    $scope.data = data; 
}); 

瞭解更多關於如何使用承諾here

+0

如果在MainCtrl控制器中調用它,並且overallcontroller持有$ scope.data info,那麼在mainctrl中調用它時如何將結果傳輸到overallcontroller中? – maria

+0

如果整體控制器需要這些數據,那麼爲什麼要將該代碼放在MainCtrl中,而不是放在overallcontroller中? –

+0

,因爲我覺得我應該在mainctrl範圍內完成一些特殊的輸入後調用更新後的數據。在頁面上使用一個控制器而不是兩個更好? – maria

-1

嘗試引用$ rootScope而不是$範圍。

這將允許控制器和工廠互相交互。

+0

你可以做一個例子嗎? – maria

0

您從您的服務回報承諾,你會聽的,要resovle,讓您的數據保持。

使用$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; 
    }) 
};