我嘗試做我的第一個angularjs應用程序,但我有一個問題。我有2個控制器(我想保留2):第一個列出項目,第二個編輯或創建一個項目。AngularsJS列表和編輯有2個控制器
當我保存的項目,或創建一個新的項目,我不能編輯另一個或創建另一個,後做一個動作形式無法加載或保存......這個問題似乎是這一行:
$scope.editPlace = {};
但我不明白爲什麼...
DEMO:
HTML:
<div ng-app="mapApp">
<div ng-controller="EditPlaceCtrl">
<form name="editPlaceForm">
<fieldset>
<label for="title">Title:</label>
<input id="title" type="text" ng-model="editPlace.title">
<input type="hidden" ng-model="editPlace.id" />
<button type="submit" ng-click="savePlace()">Save</button>
</fieldset>
</form>
</div>
<section ng-controller="PlaceCtrl">
<ul>
<li ng-repeat="place in places">
<label>{{place.title}} <a href="#" ng-click="edit(place.id)">edit</a></label>
</li>
</ul>
</section>
</div>
JS:
var mapApp = angular.module('mapApp', []);
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
$rootScope.editPlace = angular.copy(placeService.get(id));
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.savePlace = function() {
placeService.save($scope.editPlace);
$scope.editPlace = {};
}
});
mapApp.service('placeService', function ($filter) {
var uid = 3;
var places = [
{ id: 1, title: 'Item1', lat: 43.123, lng: -89.123 },
{ id: 2, title: 'Item2', lat: 43.321, lng: -89.321 }
];
this.getAll = function() {
return places;
}
this.get = function (id) {
var place, i;
for (i in places) {
if (places[i].id === id) {
return places[i];
}
}
return false;
};
this.save = function (place) {
if (place.id == null) {
place.id = this.uid++;
places.push(place);
} else {
for (i in places) {
if (places[i].id == place.id) {
places[i] = place;
}
}
}
};
});
謝謝!其作品 :) – newbee 2014-10-29 23:20:31