iKey iKey - 1 month ago 6
AngularJS Question

Angular $scope variables not updating in controller

My variables are not updating in the controller and I have no idea why.

In the view I have this code

<div ng-if="state_1">
<input ng-model='amount'> {{amount}} <!-- this binds perfectly -->
<button ng-click='submitForm()'>Submit</button>
</div>
<div ng-if="state_2">
<input ng-model='txcode'> {{txcode}} <!-- this binds perfectly -->
<button ng-click='submitCode()'>Submit</button>
</div>


In the controller:

angular.module('myapp')
.controller('RecCtrl', function($scope, $state, $rootScope, $http) {
$scope.submitForm = function(){
console.log($scope.amount); //returns undefined
}
})


I followed this answer and worked around it by passing the
amount
into
submitForm()
from the view.
But now I need to use a value from
$rootScope
but nothing shows. Nothing works in this controller except for that
$scope.submitForm()
. Every other controller is working fine.

If it will help, there are 2 states using the same controller and template like so:

//initiate payment tx
.state('rec', {
url: '/receive',
templateUrl: 'views/rec.html',
controller: 'RecCtrl'
})

//claim payment tx
.state('claim', {
url: '/claim',
templateUrl: 'views/rec.html',
controller: 'RecCtrl'
})


I use the
$state.current.name
to separate the functions. But I have tried deleting the other one, it still didn't work. Other controllers are working fine.

Answer

ng-if creates a new scope. So, you cannot directly use primitive values, use reference values.

If you use primitive values they will be local to ng-if scope. So, you cannot access them from your controller.

If you use reference value, ng-model checks if the value exists in ng-if scope, if it does not then it looks the value in parent scope which is RecCtrl scope in this case.

This link will help you to understand why you should use reference values.

angular.module('myapp')
   .controller('RecCtrl', function($scope, $state, $rootScope, $http) {
      // use a reference value
      $scope.details={};
      $scope.submitForm = function(){
         console.log($scope.details.amount);   
      }
   })

HTML

<input ng-model='details.amount'> {{details.amount}} 
<button ng-click='submitForm()'>Submit</button>
Comments