简体   繁体   中英

angularjs bind with value from server

I am creating a table that holds product information.

For each row I have an package field. The system requires that the information for packages is stored on the server as a json file.

What I am trying to do is in the ngRepeat for each row, to query the server and bind the returned value to the td.

I have an array of products that I am using for the table, and the table is created like this:

<tr ng-repeat="product in products">
    <td>{{product.value}}</td>
    <td>{{product.name}}</td>
    <td>{{getPackageNameById(product.package)}}</td>
</tr>

The getPackageNameById function does the request to the server, via a service, and returns the package object

The function:

$scope.getPackageNameById = function(packageId){
      Packages.getPackageById(packageId)
      .then(function (components) {
        console.log(components); // THIS WORKS, I SEE THE RETURNED PACKAGE OBJECT
        return components;
      }, function (error) {
        console.error(error);
      });
    };

The Service:

factory('Packages', function ($q, $http) {
    return {
      getPackageById: function (packageId) {
        var deferred = $q.defer(),
          httpPromise = $http.get('/packages/'+packageId);

        httpPromise.success(function (components) {
          deferred.resolve(components);
        })
          .error(function (error) {
            console.error('Error: ' + error);
          });

        return deferred.promise;
      },
    };
  });

The problem is that the getPackageNameById gets in to an infinite loop and the site crashes.

I would very much appreciate any suggestions on how to achieve this in the correct way TIA!

Two things:

<td>{{getPackageNameById(product.package)}}</td>

I think Angular two-way data binds doesn't work fine with function call

$scope.getPackageNameById()

Doesn't return value

So, use a property for data bind:

<tr ng-repeat="product in products">
    <td>{{product.value}}</td>
    <td>{{product.name}}</td>
    <td>{{product.packageValue.value}}</td>
</tr>

Get the information for all products:

angular.forEach($scope.products, function(product) {
  product.packageValue = $scope.getPackageNameById(product.package);
});

Define a "class" to create new objects references

var Package = function(){
    return {
        value: 0
    };
}

And, return the value correctly

$scope.getPackageNameById = function(packageId){
   var packageValue = new Package();
   Packages.getPackageById(packageId)
   .then(function (components) {
     packageValue.value = components;
   }, function (error) {
     console.error(error);
   });
   return packageValue;
 };

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