I am facing an issue with angular's two way binding and ng-value directive.
There is a method binded to ng-value
and when the value is changed else where it is not updated in the view. To solve this, I have registered a $watch
but $digest
is throwing this error . I dont know where I am going wrong and want to know the right approach in this situation.
I have posted the code below.
HTML
<div ng-app='myApp' ng-controller="myController">
<button ng-click="change()">Change</button>
<input type="text" ng-value="getData()" />
</div>
SCRIPT
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.a = 0;
$scope.getData = function() {
$scope.a = 50;
return $scope.a;
}
$scope.change = function() {
k = 1;
$scope.a = 100;
console.log($scope.a)
}
$scope.$watch('a', function() {
$scope.$digest();
})
})
When I click the button Change
the value of variable is changed but it is not updated in the view, so I tried $digest
and $apply
which is throwing this error.
$digest already in progress
Any help is greatly appreciated. Thanks in advance.
Use ng-model
:
<div ng-app='myApp' ng-controller="myController">
<button type="button" ng-click="change()">Change</button>
<input type="text" ng-model="a">
</div>
In the script, remove $scope.getData
and $scope.$watch
.
Use ng-model
to make sure that the value in the input is properly tracked. It sounds like you only want getData
to get the initial value of the input from a service. If that's correct, you can still call that function in your controller constructor:
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.getData = function() {
$scope.a = 50;
return $scope.a;
}
$scope.change = function() {
k = 1;
$scope.a = 100;
console.log($scope.a)
}
$scope.getData();
});
Then your HTML should look like this:
<div ng-app='myApp' ng-controller="myController">
<button ng-click="change()">Change</button>
<input type="text" ng-model="a" />
</div>
Try it out on plunker .
If you don't want to use ng-model
then try like this
var app = angular.module('myApp', []); app.controller('myController', function ($scope, $timeout) { $scope.myText = 50; $scope.getData = function () { return $scope.myText; } $scope.change = function () { k = 1; $scope.myText = 100; }; })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='myApp' ng-controller="myController"> <button ng-click="change()">Change</button> <input type="text" ng-value="getData()" /> </div>
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.