我正在尝试用我的json文件选择数据 $ resource 请求:
我在控制器中使用全局变量 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"
}]
答案 0 :(得分: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>