angularjs: using service to communicate between controllers

不问归期 提交于 2019-11-29 12:05:17

To access the service in your view, you need to assign it to the scope:

$scope.serviceA = serviceA;

http://jsfiddle.net/MzJsZ/

angular.module('myservices', []).factory('serviceA', function () {        
  return {

//// factory returns an object

     var serviceA= {  
      selectedItem: selectedItem,      
      ... more functions here
    };
    return serviceA;

    var selectedItem;
    ... functions go here

}

});

does this work? you were missing the return{} part,where everything goes there. if you would use service you would write just this.serviceA={...}

and your code in controller is missing $scope !

$scope.someItem= serviceA.selectedItem; 

or (i dont really know what you want) $scope.serviceA.selectedItem= someItem;

then in your span

<span>{{someItem.value}}</span>

or (i dont really know what you want) <span>{{serviceA.selectedItem.value}}</span>

PS i dont like that your controllers name is the same as object's - serviceA;

Ah ! I got it to work !

Doing :

<span>{{serviceA.selectedItem.value}}</span>

in the view wouldn't work because although the serviceA is injected in the view's controller, I did not assign it to the scope... So correct way is to do that in the controller:

angular.module('controllers').controller('someCtrl',
['$scope', 'directDebitService', function ($scope, serviceA) {
    $scope.serviceA= serviceA;
}]);

Works fine now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!