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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to use an object like so: Demo

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

1 Comment

It's object with one property (a bit ugly solution if I need only one variable, but I have no other choice probably).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.