0

it was a very simple but don't no why i can't solve it.

I am trying to convert string to integer from json, it converts 1st object but from second object it doesn't:

HTML:

<body ng-controller="myApp">
  <ul ng-repeat="vals in json_arr" ng-init="parseId(vals)">
    <li>
      <input type="number" ng-model="vals.id" />
    </li>
    <li>
      <input type="number" ng-model="vals.id1" />
    </li>
    <li>
      <input type="number" ng-model="vals.id2" />
    </li>
  </ul>
</body>

Controller:

app.controller('myApp', function($scope) {
  $scope.json_arr = [{
    'id': '1',
    'id1': '2',
    'id2': '3'
  }];

  $scope.parseId = function(val) {
    val.id = parseInt(val.id);
  }
});

DEMO PLUNKER

3 Answers 3

1

Aahhhhh that's my mistake, In parseId function i only parse val.id.

The correct 1 is:

$scope.parseId = function(val) {
  val.id = parseInt(val.id);
  val.id1 = parseInt(val.id1);
  val.id2 = parseInt(val.id2);
}
Sign up to request clarification or add additional context in comments.

Comments

1

change your code with this one

$scope.parseId = function(val) {
    val.id = parseInt(val.id);
    val.id1 = parseInt(val.id1);
    val.id2 = parseInt(val.id2);
}

or you can change your json_arr variable than you don't need to change string to int

$scope.json_arr = [{
    'id': 1,
    'id1': 2,
    'id2': 3
}];

Comments

0

Directives are executed in order from highest priority to lowest priority when defined on the same element. ng-repeat has a directive priority level of 1000, but ng-init has a directive priority of 450. ng-repeat also has a terminal property - meaning it is the last directive to execute, and no other directives can execute after it. There-in lies the problem. The ng-repeat executes first, and because it is terminal, it will not allow ng-init to execute after.

To solve this, move the ng-init to the first li below:

<body ng-controller="myApp">
  <ul ng-repeat="vals in json_arr">
    <li  ng-init="parseId(vals)">
      <input type="number" ng-model="vals.id" />
    </li>
    <li>
      <input type="number" ng-model="vals.id1" />
    </li>
    <li>
      <input type="number" ng-model="vals.id2" />
    </li>
  </ul>
</body>

This works because ng-model has a priority of 0, so it will execute after ng-init.

[EDIT]

I realized there is a logic error in the code you posted. The other two answers have already addressed it, but I'll post it again here for completeness:

$scope.parseId = function(val) {
    val.id = parseInt(val.id);
    val.id1 = parseInt(val.id1);
    val.id2 = parseInt(val.id2);
}

Comments

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.