0

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)?

Community
  • 1
  • 1
mkczyk
  • 2,460
  • 2
  • 25
  • 40

2 Answers2

1

You have to use an object like so: Demo

app.service('dataService', function() {
    this.variable = {a:''};
});
VRPF
  • 3,118
  • 1
  • 14
  • 15
  • It's object with one property (a bit ugly solution if I need only one variable, but I have no other choice probably). – mkczyk May 08 '16 at 01:59
1

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95