maria maria - 3 months ago 26
AngularJS Question

update $scope info from another controller

How can i make the testservice factory return the result from the post request?, or make the app, factory update some

$scope
details thats within the
overallcontroller
?

how can i update information within the
overallcontroller
from another controller?

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);




}]);


example 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>

Answer

Change your service to

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

And in your controller, do call the service, and get the results back in the promise:

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

Read more about how to use promises here

Comments