I have an standard Angular.js
App. I have a service
like this:
app.service("myService",function(){
this.variable = "world";
});
In my controller
s I can use this service
like this:
app.controller("loginCtrl",function($scope,myService){
$scope.value = myService.variable; // this works
});
But my problem is that I cant access to service
values inside my HTML template:
<h1>hello {{myService.variable}}</h1> //this doesn't work
If I store service
variable in a temp variable inside my controller
, I can use that temp inside the template but i don't like this method. is there any proper way?
Your scope variable is what angular will use to bind to your view. Your view does not have access to your services as they are not part of your scope.
The controllers purpose if to bring all your services together and provide that data to your view/scope.
You generally don't expose your services directly to your scope. They usually provide generic single reuseable pieces of logic. This makes them greatly re-usable and easily testable. However you could data bind directly to them by
$scope.myService = myService
;
However i would personally avoid this like the plague as a service is used through the entirety of your app, changes your view makes to the service will be reflected throughout your application. This will make your service un-trustable is structure and most likely useless.
I created a fiddle showing : http://jsfiddle.net/5g3tnq17/
var app = angular.module('test', [])
.controller('testController', function($scope, testService){
//When you modify $scope.testService
$scope.testService = testService;
})
.service('testService', function(){
this.prop = 'hi';
})
.directive('testDirective', function(testService){
return {
type: 'EA',
template: '<button ng-click="get()">get service value</button>{{serviceValue}}',
link: function($scope, elem, sttr){
//Test service will also be modified anywhere else you use it
$scope.get = function(){
$scope.serviceValue = testService.prop;
}
$scope.get();
}
}
});
To access it in your html you need to bind it to your controller and then use $scope
in your html like this.
Service
app.service("myService",function(){
this.variable = "world";
});
Controller
app.controller("loginCtrl",function($scope,myService){
$scope.value = myService.variable;
});
HTML
<h1>hello {{value}}</h1>
You never inject your services in your HTML, only in your controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With