我在下面有以下 Angular 代码。我注意到当我调用 ng-click="update($index, list.name)" 来更新名称字段时,它会在我的 JSON 列表中为 ID 创建一个新的键/值对,这是不必要的。此外,我的所有其他字段,如类型、CDN 等都被清除了。我只想更新名称字段。谢谢!
var tools = angular.module("tools", ['ngResource'])
tools.config(function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
});
$routeProvider.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
});
$routeProvider.otherwise({
redirectTo: '/home'
})
});
tools.controller("HomeController", function($scope, fetchData, containItems, fetchData) {
$scope.arrayofModel = ["nothing"];
$scope.clearSearch = function() {
$scope.search = "";
$scope.name2 = "";
}
$scope.name2 = "";
$scope.search = "";
//READ
$scope.record = fetchData.query();
//CREATE
$scope.addNew = function(name, $location) {
//Create the forum object to send to the back-end
var forum = new fetchData($scope.addNew1);
//Save the forum object
forum.$save(function(response) {
$scope.record.unshift(response);
//$scope.record = fetchData.query();
}, function(response) {
//Post response objects to the view
$scope.errors = response.data.errors;
});
}
//DELETE
$scope.destroy = function(index) {
//alert($scope.record[index]._id.$oid);
//return false;
//Tell the server to remove the object
fetchData.delete({
id: $scope.record[index]._id.$oid
}, function() {
//If successful, remove it from our collection
$scope.record.splice(index, 1);
});
}
//UPDATE
$scope.update = function(index, newName) {
fetchData.update({
id: $scope.record[index]._id.$oid,
name: newName
}, function() {
console.log('posted');
$scope.record = fetchData.query();
});
}
});
tools.controller("AboutController", function($scope) {});
tools.factory('fetchData', function($resource) {
return $resource('https://api.mongolab.com/api/1/databases/frameworks/collections/list/:id?s={name: 1}&apiKey=_QnS_M-Iz9-RCKJNmVYEMvvaYL', {}, {
'get': {
method: 'GET'
},
'save': {
method: 'POST'
},
//CREATE
'query': {
method: 'GET',
isArray: true
},
//READ
'remove': {
method: 'DELETE'
},
'update': {
method: 'PUT',
params: {
id: "@id"
}
},
//UPDATE
'delete': {
method: 'DELETE',
params: {
id: "@id"
}
}
}) //DELETE
});
这也是我的观点:
<tbody>
<tr ng-repeat="list in record | filter: {type:name2, name: search}">
<td>{{list._id.$oid}}</td>
<td><input ng-model="list.name"></td>
<td>{{list.type}}</td>
<td><img src="{{list.logo}}" /></td>
<td><a target="_blank" href="{{list.url}}">URL</a></td>
<td><a ng-show="list.CDN != ''" href="{{list.CDN}}">CDN</a></td>
<td><a target="_blank" class="btn btn-primary btn-large" href="{{list.download}}" ng-click="putConsole(list.name)">Download</a></td>
<td><a target="#" class="btn btn-primary btn-large" ng-click="destroy($index)">Delete!</a></td>
<td><a target="#" class="btn btn-primary btn-large" ng-click="update($index, list.name)">Update!</a></td>
</tr>
<!--<tr><span ng-show="totalCount.length == '0'">No results found. Please reset your search and try again!</span></tr>-->