我是AngularJS的新手,无法弄清楚如何执行以下操作:
如何更新列出同一$ scope对象的两个不同页面?
基本上,我有一个管理页面,我可以在数据库中添加/更新/删除项目,以及另一个列出这些项目的页面。添加/更新/删除项目后,我希望立即看到更改。这在管理页面中没问题,但首页呢?
提前感谢您提供任何帮助!
我的代码看起来像这样:
的script.js
var menuApp = angular.module('menuApp', []);
menuApp.factory("serverRequest", function($http) {
return {
getDishes: function() {
return $http.get('../request.php?action=get')
.then(function(result) {
return result.data;
});
},
addDish: function (dish) {
return $http.get('../request.php?action=add', {
params: {data : dish}
})
.then(function(result) {
return result.data;
});
}
}
});
function appController($scope, serverRequest) {
// Add new dish
$scope.addNewDish = function(dish) {
serverRequest.addDish(dish);
$scope.dishes.push(dish);
}
// Get menu dishes in DB
$scope.dishes = serverRequest.getDishes().then(function(d) {
$scope.dishes = d;
});
}
admin.html和index.html
<div ng-controller="appController">
<ul>
<li ng-repeat="(key,dish) in dishes">
<a ng-click="editDish(dish.id, key)">{{dish.name}}</a>
</li>
</ul>
</div>
答案 0 :(得分:1)
试试这个
var menuApp = angular.module('menuApp', []);
menuApp.service("serverRequest", ['$http', function($http) {
return {
getDishes: function() {
return $http.get('../request.php?action=get');
// You want to use your service to return a promise
// to you - you won't actually get the data until
// the promise resolves - so put the 'then' in your controller
// when the request is made
// then(function(result) { return result.data; })
},
addDish: function (dish) {
return $http.get('../request.php?action=add', { params: {data : dish} });
// see comment above...
}
}
}]);
menuApp.controller('appController', ['$scope', 'serverRequest',
function ($scope, serverRequest) {
// Add new dish
$scope.addNewDish = function(dish) {
serverRequest.addDish(dish);
$scope.dishes.push(dish);
}
// Get menu dishes in DB
$scope.dishes = serverRequest.getDishes().then(function(d) {
$scope.dishes = d;
}
}]);