2017年11月22日 星期三

How to push value into structured array in Angularjs v1.x

How to push value into structured array in Angularjs v1.x 

Background
- angularjs v1.x
          
  // define $scope variables for store result
  $scope.roles = [];

        var getSomething = function () {            
            return $http({
                method: 'GET',
                url: 'http://www.somewhere.com/GetSomething'
            }).then(function successCallback(response) {
    // Assume return value is something like "ValueA, ValueB, ValueC, ValueD"
                angular.forEach(response.data, function(value, key){
     
     //target structure like this
     //  roles [ 
     //   {
     //   value : "ValueA",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueB",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueC",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueD",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   }     
     //       ]    
                    $scope.roles.push( {value:value, attr1:false, attr2:"attr2 value"} )
                });                
            }, function errorCallback(response) {                
            });
        };

沒有留言:

張貼留言