【发布时间】: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