简体   繁体   中英

AngularJS binding not updating model

I recently started exploring AngularJS. I saw some similar questions but I'm quite sure that there isn't any scope problem here. (or maybe my understanding of scope isn't clear.)

JS Code:

var app = angular.module("myApp", []);
app.controller("myController", function($scope){
$scope.b=50000
$scope.apr=10
$scope.hc=$scope.b/$scope.apr
...
})

HTML:

<div ng-app="myApp" ng-controller="myController">
<span class="inp-heading">b:</span>
<input ng-model="b" type="number" step="1000" min="0" />
<input ng-model="apr" type="number" step="1" min="0" />
{{b}} <br /> <!-- this updates on input value change -->
{{hc}} <br /> <!-- this does NOT update on input value change -->
{{b/apr}} <br /> <!-- this updates on input value change -->

As mentioned in the comments (in the HTML code above) $scope.hc doesn't change. This isn't the only issue actually, I'm facing similar trouble while binding array values to input boxes.

Any help would be appreciated.

your hc won't update automatically, if needed then it should be a function like

var app = angular.module("myApp", []);
app.controller("myController", function($scope){
  $scope.b=50000
  $scope.apr=10
  $scope.hc= function() { return $scope.b/$scope.apr; };
  ...
})

and then in your partial it should be (instead of hc , it will be hc() )

<div ng-app="myApp" ng-controller="myController">
<span class="inp-heading">b:</span>
<input ng-model="b" type="number" step="1000" min="0" />
<input ng-model="apr" type="number" step="1" min="0" />
{{b}} <br /> 
{{hc()}} <br /> 
{{b/apr}} <br /> 

Since controller function is not going to be reinvoked when you just change some of the models, the value of $scope.hc won't be recalculated. You need to update it manually or get recalculated value somehow before rendering. Couple of approaches.

1. ngChange directive

Use ngChange directive (kind of onchange event) to update $scope.hc value:

var app = angular.module("myApp", []);
app.controller("myController", function($scope){
  $scope.b = 50000
  $scope.apr = 10
  $scope.hc = $scope.b/$scope.apr

  $scope.onChange = function () {
    $scope.hc = $scope.b/$scope.apr
  }
})

HTML

<input ng-model="b" ng-change="onChange()" type="number" step="1000" min="0" />
<input ng-model="apr" ng-change="onChange()" type="number" step="1" min="0" />

2. Using getter

You can use old gold ES5 property getter here when defining hc as a property of $scope object:

var app = angular.module("myApp", []);
app.controller("myController", function($scope){
  $scope.b = 50000
  $scope.apr = 10

  Object.defineProperty($scope, 'hc', {
    get: function () {
      return $scope.b/$scope.apr
    }
  })
})

HTML won't change in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM