I am stuck into a problem where I am suppose to get all the ng-models which are declared as ng-model="a['keyX']
and initialize them to 0
before the user starts giving inputs..
Due to some reasons I cannot use ng-value
.
I tried to get $scope.a
into my initializeToZero()
function. It returns an empty json object.
I even tried using $scope.$apply()
but my bad luck.
All I get is only an empty json object.
Is there any way I can initialize them all in the controller irrespective to number of inputs and keys?
The names of keys would be all different... I just provided generic key names here... So make sure that you do not hard code it.
I have mentioned ng-controller
for the snippet but I am using ui.router
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
initializeToZero();
function initializeToZero() {
if (!$scope.$$phase) {
$scope.$apply();
console.log($scope.a);
} else {
setTimeout(initializeToZero, 1000);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" ng-init="a = {}">
<input type="number" ng-model="a['key1']">
<input type="number" ng-model="a['key2']">
<input type="number" ng-model="a['key3']">
<input type="number" ng-model="a['key4']">
<input type="number" ng-model="a['key5']">
<input type="number" ng-model="a['key6']">
<input type="number" ng-model="a['key7']">
<input type="number" ng-model="a['key8']">
</div>
Finally Cracked it... A bit of dirty coding has to be done.. But its alright.. here is the code..
function application(){
$('input[ng-model^="a"]').each(function(){
$(this).val(0);
});
}
$scope.initializeToZero = function(){
console.log("Called initializeToZero");
if(!$scope.$$phase)
{
$scope.$apply(application);
console.log("Applied");
}
else{
console.log("REDOING");
setTimeout($scope.initializeToZero,1000);
}
}
$scope.initializeToZero();