BaneStar007
BaneStar007

Reputation: 417

Can I create a service that plugs directly to my controller or maybe component

I may be wrong, but I was under the impression that I could access my service and have it display the data directly.

I.e. I can inject my service and have read/write access to it from multiple components, Its easy enough to do, but if I want the services data to be displayed, I need to copy it to the controller to let $scope/vm/this to then hook it into the HTML template. but that means any changes that happen at the DOM level, need to be watched/triggered to tell the service that it changed, Which I'd like to be automatic.

I'm essentially trying to save time asking if it can be done, Its something I've been curious about, has anyone set it up before and got it working? Would you be so kind as to elaborate?

Upvotes: 0

Views: 40

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13488

At this case, you can create service as you always do, but then assign it to $rootScope property(for example service) at run method, so you can use it via service.name or service.test literals at your templates without restrictions, because all $scopes are inherited from $rootScope. Also you not need to inject service to your particular controller, you can use it at once via template:

var app = angular.module('app', []);

app.factory('myservice', function(){  
  return {
    test: function(){
      console.log(this.name);
    },
    name: 'Tom'
  };
}).controller('ctrl', function($scope, myservice){  
  $scope.local = 'from local ctrl';  
  $scope.serviceName = function(){
    return myservice.name;
  }
})

app.run(function(myservice, $rootScope){
  $rootScope.service = myservice;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='service.name'/> 
  {{serviceName()}}
  <br>
  <input type='button' ng-click='service.test()' value='service.test'/>  
  <br>
  <br>
  <input type='text' ng-model='local'/>  
<div>

Upvotes: 1

Related Questions