James Frankline
James Frankline

Reputation: 1

watch the value in angularjs

how to watch the array value of ng-model in angularjs i have created fiddle but does not work Please take a look and suggest.

Thanks

<div ng-app ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
        <table>
            <tr ng-repeat="user in profiles track by $index">
                 <td>
                    <input
                      type="text"
                      name="parktime_{{user.user_id}}"
                      ng-model="orderItems[user.user_id].parktime"
                      >
                 </td>
            </tr>
        </table>
        </div>
</div>



 function ParentCtrl($scope) {
    }

    function ChildCtrl($scope) {
        $scope.parkOptions = {};
        $scope.profiles = [
            {user_id: '01', park_name: 'England Park'},
            {user_id: '02', park_name: 'France Park'}
        ];
 $scope.orderItems = {};
$scope.orderItems.parktime = "Test";

        $scope.$watch('orderItems[profiles.user_id].parktime', function(newVal, oldVal){
            console.log(newVal);
        })

    }

http://jsfiddle.net/w5vskLfc/59/

Upvotes: 0

Views: 55

Answers (2)

Brian
Brian

Reputation: 5049

I suggest you use ng-change instead. You can't use watch this way, it is to watch a single property instead.

I've also updated your model to use ng-init. This is something you should be careful with using, but in your case, you need to have an key defined at each position of your orderItems object. If you will always statically assign these, I recommend iterating through them once and creating a key that way instead.

HTML

      <input type="text" name="parktime_{{user.user_id}}"
      ng-init="orderItems[user.user_id] = {}"
      ng-model="orderItems[user.user_id].parktime"
      ng-change="onChange(user.user_id)">

JS

   $scope.onChange = function(items) {
        console.log(items);
   }

Upvotes: 2

Harshal Limaye
Harshal Limaye

Reputation: 292

You are trying to access indexes which does not exist. profiles is an array of objects and I don't think there is anything available on profiles.user_id index. Also, I don't think orderItems[profiles.user_id] will work as that index also doesn't exist.

Upvotes: 0

Related Questions