ceth
ceth

Reputation: 45285

How to bind variables to INPUT dynamically

I have an object in the controller which value I am getting from http GET request:

$scope.myObj = {

      id1: "1",
      id2: "5",
      id3: "",
      id4: ""
    };

It can have any number of fields (id...) with any values. But if id-k is not empty all id-n where n < k is not empty too.

I need to bind to INPUT last not empty field of the object. What is best way to do it?

Here is a plnkr

Update: This object is a position in the classificator. In my example ID of position is 1.5. I need to allow edit only last position in the classification. The user can change 5 to 6, 7 or anything else, but it can not change 1 segment

If the object will be

$scope.myObj = {

          id1: "2",
          id2: "5",
          id3: "4",
          id4: "8"
        };

The classification is 2.5.4.8 and user must be able edit only last segment - 8.

Upvotes: 2

Views: 42

Answers (2)

potatopeelings
potatopeelings

Reputation: 41075

Controller

...
$scope.myObj = {
  id1: "1",
  id2: "5",
  id3: "6",
  id4: ""
};

$scope.segments = Object.keys($scope.myObj)
  .filter(function(key) {
    return $scope.myObj[key];
  })
  .sort(function(a, b){
    return Number(a.replace('id', '')) - Number(b.replace('id', ''));
  });
 ...

HTML

<span ng-repeat="segment in segments">
   <span ng-if="!$last">{{ myObj[segment] }}</span>
   <input ng-if="$last" ng-model="myObj[segment]">
</span>

<p>{{ myObj }}</p>

Plnkr - https://plnkr.co/edit/8C9lLLdCvvzFinaOXqtd?p=preview


Original Answer

You can calculate the last non blank id in the controller and set it to a scope variable. Something like

$scope.myLast = $scope.myObj['id' + Object.keys($scope.myObj).reduce(function(a, key){
  if ($scope.myObj[key]) {
    var idNum = Number(key.replace('id', ''));
    a = Math.max(a, idNum)
  }
  return a;
}, -Infinity)];

Note - you can't rely on the order of keys, so you can't actually assume that the last key is the biggest one.


Plnkr - https://plnkr.co/edit/apy8qZNJNK4Q23J5Ja4N?p=preview

Upvotes: 1

Vasu Sheoran
Vasu Sheoran

Reputation: 215

I need to bind to INPUT..

So it seems ,what you have is , a list of objects where the no. of elements in the list can vary.. and you want to bind all of them to <input>

If so then this would do the job:

<div ng-init="tempName = key" ng-repeat="(key, value) in myObj">
    <label for="{{key}}" >{{key.toUpperCase()}}</label>
    <input name="{{key}}" id="{{key}}" type="text" ng-model="myObj[tempName]" />
</div>

here's an awesome plunkr doing just that

EDIT:

To ignore the empty fields : use this

Upvotes: 0

Related Questions