To add an answer to Ed Hinchliff, there is one more thing you could try. As other people have noted, factories and services are solitary. However, there is one key difference between the services and factories we can use to do this: the services provide an instance of the service function ( new ServiceFunction() ), and the factory is the value returned by calling the function reference passed to the module. This information is explained in this stackoverflow:
service-vs-provider-vs-factory
So basically this means that we can create a function in the factory, add properties to its prototype, and then create an instance of this on the controller, passing the arguments we need. Here is a very simple example:
Suppose we have our angular module for the app global variable. First, we create a Ui-Router state with a permission attribute:
app.config(function ($stateProvider) { $stateProvider .state('example', { url: '/example', templateUrl: 'app/example/example.html', controller: 'ExampleCtrl', resolve: { repeatValue: ['$q', '$timeout', function($q, $timeout){ var deferred = $q.defer(); $timeout(function(){ deferred.resolve( parseInt(Math.random() * 100) ); }, 3000); return deferred.promise; }] } }); });
To represent an asynchronous action, we use the $q and $timeout service provided by the angular core to return a promise to the reslove object, which resolves after three seconds.
Now we need to create our factory using the method described earlier:
app.factory('Greeter', function () { // Function var Greeter = function(repeat){ this.repeat = repeat; }; // Prototype Greeter.prototype.repeatedHi = function() { var array = []; console.log(this); for (var i = 0; i < this.repeat; i++){ array.push('Hi'); } return array; }; // Public API here return Greeter; });
Here we created the Greeter factory constructor. Now we can create an instance of the factory by passing the arguments we need. In this example, we need to give the constructor a value of repeat . If we want to enter an asynchronous value in the factory using the resolve ui-state property, we can do this on the controller:
app.controller('ExampleCtrl', function ($scope, Greeter, repeatValue) { $scope.repeatValue = repeatValue; var greeter = new Greeter(repeatValue); $scope.greetingsArray = greeter.repeatedHi(); });
$scope.greetingsArray will populate the repeatValue string "Hi".
Hope I said clearly, hope this helps.