Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a variable inside a service to html template in an Angular App

I have an standard Angular.js App. I have a service like this:

app.service("myService",function(){
   this.variable = "world";
});

In my controllers 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?

like image 923
Fcoder Avatar asked Feb 09 '23 01:02

Fcoder


2 Answers

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();
    }
   } 
});
like image 89
ste2425 Avatar answered Feb 11 '23 14:02

ste2425


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.

like image 36
Joe Lloyd Avatar answered Feb 11 '23 15:02

Joe Lloyd