Reputation: 2848
For instance this service :
services.factory('ElementsService', function () {
var currentElement = 'default element';
var service = {
getCurrentElement: function () {
return currentElement;
},
setCurrentElement: function (elmnt) {
currentElement = elmnt;
}
}
return service;
I often find useful to do the following from controllers :
controllers.controller('ElementsCtrl', function($scope, ElementsService) {
$scope.elementsService = ElementsService;
});
To be able to bind the service variables in the html and stay up to date if the variables get changed by some other controller or service. Like so :
<p>The current element is : {{elementsService.getCurrentElement()}}</p>
My question is : is this ok or should I avoid doing this?
Upvotes: 4
Views: 67
Reputation: 171679
Sure the concept is OK and saves having to make a number of different scope variables
Another way you can do it is
angular.extend($scope, ElementsService );
Then in the view you immediately have access to the same data and methods that are returned from the factory
<button ng-click="setCurrentElement(someObj)">test</button>
Upvotes: 4