2

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>

2
  • Have you tried to call initializeToZero in ng-init, and put "a = {}" as first line in initializeToZero function? Or call initializeToZero in angular.element(document).ready function? Commented Jun 30, 2016 at 11:10
  • Yes I tried that.. It didn't work either.. @RicardoPontual Commented Jun 30, 2016 at 11:29

5 Answers 5

2

First of all, it's a good practice to use a.key1 instead of a['key1']. Secondly, if you want to assign zero to all a values, then use the map function at the start of your controller:

$scope.a.map(function(item) { return '0'; });

That will return a with all items set to zero.

Sign up to request clarification or add additional context in comments.

1 Comment

It didn't work for me... however you can edit and upload a code snippet to explain your point.
1

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();

Comments

1

You need to make sure your data is loaded before you display the input fields:

HTML:
<div ng-app="myApp" ng-controller="myCtrl" data-ng-init="getValues()">
 <div ng-show="dataLoaded">
  <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>
</div>


IN YOUR CONTROLLER:
$scope.getValues= function () {
 // Do your initialization here
 // For example:
 angular.forEach($scope.a, function(key, value){
  $scope.a[key] = 0;
 })
 // Set dataLoaded to true
 $scope.dataLoaded = true;
}

CODEPEN: http://codepen.io/giannidk/pen/KrmgNL?editors=1011

2 Comments

Read the question again.. The name of key is not fixed.. You have hard coded it...@gianni
Not enough... The inputs would be stuck on html along with ng-models
0

EDIT: Sort of a hacky way, but I guess it'll get the job done.

HTML:

<div ng-app="myApp" ng-controller="myCtrl">
  <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['some']">
  <input type="number" ng-model="a['other']">
  <input type="number" ng-model="a['keys']">
</div>

JS:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
  var inputs = document.getElementsByTagName('input');
  $scope.a = {};
  for (var i=0; i<inputs.length; i++) {
    $scope.a[inputs[i].getAttribute('ng-model').replace(/^a\[\'(.*)\'\]$/, '$1')] = 0;
  }
});

jsFiddle

8 Comments

You hard-coded it to length 8.. It should be dynamic
You can loop through <input type="number"
@TirthrajBarot I figure getting the number of inputs is pretty trivial, and wasn't the core of the problem you were experiencing, so I didn't bother with it. I've edited my answer.
nope... Check the question again.. I have mentioned that the solution should be such that number of keys may be dynamic and the names would also be dynamic... its not just an array of keys from 1 to 8... Its different @LawrenceWebDev
@TirthrajBarot Do you have control over how the <input> elements are generated? Or are they stuck as the form <input type="number" ng-model="a['anykey']">
|
0

you should first defined the function initializeToZero

js:

angular.module('myApp', [])
  .controller('myCtrl', function($scope, $parse) {

    $scope.a = {};

    $scope.initializeToZero = function() {
     var temp = "key";
     for(var i = 0; i < 8; i++){
     var count = i + 1;
     var model = temp + count;
     var result = $parse(model);
     result.assign($scope.a, 0);
     console.log($scope.a);
 } 
}   

      $scope.initializeToZero();         

  });

html:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <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>

6 Comments

$scope.a is suppose to be a json object and not an array.
it would be great if you could only console all the keys.
@TirthrajBarot, sorry, i have update it to json object and assign it value, please have a try!
@TirthrajBarot i have updated the code once more, pls check it
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.