Search code examples
angularjsangularjs-scopeangularjs-service

AngularJS bind variable from service to controller


Can I bind only variable (not object) from service to controller?

For bind object, it works (from this answer):

<div ng-controller="myCtrl1">
  1st Controller
  <input type="text" ng-model="model1.prop1"/>
  <input type="text" ng-model="model1.prop2"/>
</div>
<div ng-controller="myCtrl2">
  2nd Controller
  <input type="text" ng-model="model2.prop1"/>
  <input type="text" ng-model="model2.prop2"/>
</div>

app.service('dataService', function() {
  this.model = {
    'prop1': '',
    'prop2': ''
  };
});

app.controller('myCtrl1', function($scope, dataService) {
  $scope.model1 = dataService.model;
});


app.controller('myCtrl2', function($scope, dataService) {
  $scope.model2 = dataService.model;
});

Demo plnkr.

But I need only one variable (not object with properties).

<div ng-controller="myCtrl1">
  1st Controller
  <input type="text" ng-model="variable1"/>
</div>
<div ng-controller="myCtrl2">
  2nd Controller
  <input type="text" ng-model="variable2"/>
</div>

app.service('dataService', function() {
  this.variable = '';
});

app.controller('myCtrl1', function($scope, dataService) {
  $scope.variable1 = dataService.variable;
});


app.controller('myCtrl2', function($scope, dataService) {
  $scope.variable2 = dataService.variable;
});

Demo plnkr.

It don't work. Why?

Is there nice way to this (without object with only one property or without $watch)?


Solution

  • It will work by setting the scope variable to the dataService object reference and the ng-model attributes to the reference property.

    JS

    app.controller('myCtrl1', function($scope, dataService) {
      $scope.ds1 = dataService;
    });
    
    app.controller('myCtrl2', function($scope, dataService) {
      $scope.ds2 = dataService;
    });
    

    HTML

    <div ng-controller="myCtrl1">
      1st Controller
      <input type="text" ng-model="ds1.variable"/>
    </div>
    
    <div ng-controller="myCtrl2">
      2nd Controller
      <input type="text" ng-model="ds2.variable"/>
    </div>
    

    The rule of thumb with ng-model is always include a "dot".

    The DEMO on PLNKR.