【问题标题】:How to select an item from json data with ngResource?如何使用 ngResource 从 json 数据中选择一个项目?
【发布时间】:2015-08-22 02:40:49
【问题描述】:

我正在尝试使用
$resource 请求从我的 json 文件中选择数据:

我在控制器中使用全局变量 productSelected

但是当我用 ng-model 更改它的值时,这不会对模型产生影响,并且参考值仍然相同!

请问有人有意见吗?

这是我的代码:

  var myApp = angular.module('myApp', ['ngResource']);

            myApp.factory('Produits',['$resource', function ($resource) {
                return $resource('data/produits.json/:id',{id: "@id"},
                         {
                     'get':    {method:'GET'},
                     'save':   {method:'POST'},
                     'query':  {method:'GET', isArray:true},
                     'remove': {method:'DELETE'},
                     'delete': {method:'DELETE'}

                         }
                );
            }]);
    myApp.controller('produitsCtrl', function($scope, $http,Produits,$log) {

     $scope.productSelected=0;

                 Produits.query(function(data){ 
                     $scope.produits=data; 
                     $scope.reference=$scope.produits[$scope.productSelected].reference ;
                     });

      });
        <div ng-app="myApp" >

                <div ng-controller="produitsCtrl"> 

                Product : <input type="text" ng-model="productSelected"/> {{ productSelected }} <br/>
                Reference : {{reference}}
                </div>
            </div>

produits.json

[{
"id" : 1,
"reference": "AA"
},
{
"id" : 2,
"reference": "BB"
}]

【问题讨论】:

  • 可能是因为您的 Produits.query 只被调用一次,即使在使用输入文本框更改 $scope.productSelected 的值之后。所以我认为您必须每次都调用 Produits.query是 productSelected 值的变化。
  • 是否有其他解决方案可以避免每次都调用查询,因为我有很多项目属性(id、reference、name、type..etc)

标签: html json angularjs ngresource


【解决方案1】:

看看这段代码可能对你有帮助

<body ng-app="myApp" data-ng-controller="MainCtrl" id="div1">
 Product : <input type="text" ng-model="productSelected" ng-change="fun(productSelected)"/> {{ productSelected }} <br/>

 Reference :<p ng-model="reference"> {{reference}} </p>


 <script>
  var app = angular.module('myApp', []);

  app.controller('MainCtrl', function($scope){


    $scope.productSelected=0;
    $scope.produits= [{
            "id" : 1,
            "reference": "AA"
            },
            {
            "id" : 2,
            "reference": "BB"
            }];
     $scope.reference=$scope.produits[$scope.productSelected].reference;
   $scope.fun=function(val){
    //alert(val)
     if(val!=undefined && val!=null && val!='')
    $scope.reference=$scope.produits[$scope.productSelected].reference;
    else
     $scope.reference=$scope.produits[0].reference; 
   };
    });
  </script>
</body>

【讨论】:

  • Thks 很多,但这里你不使用 ngResource 服务在控制器中注入 Produits,我正在寻找如何优化我的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2023-01-09
  • 2017-05-28
  • 2021-11-03
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多