简体   繁体   中英

Angular js $watch on multidimensional array?

hello friends below are my array.

data.php file

$array = array(
   '0' => array(
            'id' = 1,
            'name' = 'test',
            'key' = array(
                       '0' = 'key1',
                       '1' = 'key2',
                       '2' = 'key3'
                    )
         ),
   '1' => array(
            'id' = 3,
            'name' = 'test3',
            'key' = array(
                       '0' = 'key7',
                       '1' = 'key8',
                       '2' = 'key9'
                    )
         ),
     '2' => array(
            'id' = 15,
            'name' = 'test30',
            'key' = array(
                       '0' = 'key4',
                       '1' = 'key5',
                       '2' = 'key6'
                    )
         )
);
echo json_encode($array);

below are my js code.

$http({method: 'GET', url: $rootScope.serverURL+'data.php'}).
  success(function (data, status, headers, config) {
      $rootScope.simpleData = data;
  }).
  error(function (data, status, headers, config) {

  });

$scope.$watch('page + numPage + simpleData', function() {
    console.log('working');    
},true);

this is working fine now i want to set want on "key".

$scope.$watch('page + numPage + simpleData.key', function() {
    console.log('not working');    
},true);

this code is not working when i write this code like this is working fine.

$scope.$watch('page + numPage + simpleData[0].key', function() {
    console.log('working');    
},true);

when i write js like it is working fine. angular js watch on key but only for "0" Element. in the array i have lot's of elements how can i watch on all elements "Key".

please help

thank you

$watch ing "simpleData.key" doesn't work because $scope.simpleData.key === undefined .

If you're trying to deep-watch an array, you could add true as third parameter to $watch , which does a deep-watch, but that comes at a significant cost to performance. Every $digest cycle would have to deep-level compare your array.

$watch("simpleData", function(){...}, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM