cdz cdz - 4 months ago 17
Javascript Question

Angular ng-model not updating after typing into number input

So basically I'm creating a simple app with two controllers.

ControllerA
button increments
ControllerB
number input and vicer versa.

The problem is that
$scope.total
is not updating after typing into number input manually, and I don't know what would be the best way to achieve this.

HTML

<div ng-app="tabsApp">

<div id="tabOne" class="tabcontent">
<div ng-controller="tabOneController as vm">
<input type="button" value="increment value in tab 2" ng-click="vm.sumar()"/>
<input type="number" ng-model="vm.totalB.value">
</div>
</div>


<div id="tabTwo" class="tabcontent">
<div ng-controller="tabTwoController as vm">
<input type="button" value="increment value in tab 1" ng-click="vm.sumar()"/>
<input type="number" ng-model="vm.total.value">
</div>
</div>

</div>


JS

var app = angular.module('tabsApp', []);
app.controller("tabOneController", controllerA);
app.controller("tabTwoController", controllerB);
app.service('myData', function() {

var data = {
value: 0
}, dataB = {
value: 0
};

this.addItem = function (value) {
data.value = value;
}

this.getItem = function() {
return data;
}

this.addItemB = function (value) {
dataB.value = value;
}

this.getItemB = function() {
return dataB;
}

});



function controllerA(myData){

var scope = this;
scope.total = 0;

scope.sumar = function(){
scope.total++;
myData.addItem(scope.total);
}

scope.totalB = myData.getItemB();
}

function controllerB(myData){

var scope = this;
scope.totalB = 0;

scope.sumar = function(){
scope.totalB = myData
scope.totalB++;
myData.addItemB(scope.totalB);
}

scope.total = myData.getItem();

}

Answer

Here's a working example based on your code : Plunker

function controllerA(myData){

  var scope = this;
  scope.total = 0;

  scope.sumar = function(){
    scope.total = myData.getItem().value;  // added this line
    scope.total++;
    myData.addItem(scope.total);
  }

  scope.totalB = myData.getItemB();
}

function controllerB(myData){

  var scope = this;
  scope.totalB = 0;

  scope.sumar = function(){
    scope.totalB = myData.getItemB().value;  // modified this line
    scope.totalB++;
    myData.addItemB(scope.totalB);
  }

  scope.total = myData.getItem();

}
Comments