Ryuu
Ryuu

Reputation: 121

AngularJS $scope in a factory

Is it possible to use a scope in a factory then using it on multiple controllers ? I'm not really up to writing the same code in every controller, it'll be a pain to work on it ^^

Here's my current idea.

.factory('FactoryName', function($scope, $routeParams, $http) {
    return {
        search : function(str, http) {
            var url = str+'.json';
            return $http.get(url).success(http).error(function() {
                alert('Unable to get back the data');
            });
        }
        httpSuccessPaper : function(response) {
            $scope.papers = response;
        }

This way I only have this code once and all my controller are able to use the json of "reference". I could also write something like ng-repeat="p in papers" in some view.

Here is the way I call it in my controller :

.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
    function($scope, $routeParams, $http, FactoryName) {

        FactoryName.search("Paper",FactoryName.httpSuccessPaper).then(function(){
            $scope.paper = getByIdPa($scope.papers,$routeParams.id);
        })

It seems a bit strange to me and I'm almost sure I'm trying something impossible. I would like your opinion. Thank you !

Upvotes: 0

Views: 357

Answers (2)

Sean Clark Hess
Sean Clark Hess

Reputation: 16059

You don't want Services dealing with scopes. It's ok to repeat just the setting the scope part.

.factory('FactoryName', function($scope, $routeParams, $http) {
  return {
    search : function(str) {
        var url = str+'.json';
        return $http.get(url)
    }

Then the controller:

.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {

    FactoryName.search("Paper").then(function(papers){
        $scope.paper = getByIdPa($papers,$routeParams.id);
    })

Upvotes: 1

smallg
smallg

Reputation: 216

you can do it like this:

angular.module('apiServices', ['ngResource'])
.factory('ExampleService', ['$http', 'serviceUrl', function ($http, serviceUrl) {
    return{
        getInteractions: function () {
            return $http({method: 'GET', url: serviceUrl + 'ctest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
        },
        getRoots: function () {
            return $http({method: 'GET', url: serviceUrl + 'ntest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
        },
        getLogging: function (params) {
            return $http.post(serviceUrl + 'atest', params);
        },
        getMessage: function (params) {
            return $http({method: 'GET', url: serviceUrl + 'btest', params: params, headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
        }
    };
}]);

Upvotes: 1

Related Questions