这是我在 app.js 文件中的 AngularJs 代码
var CarApp = angular.module('CarApp',['ngResource'])
CarApp.config(function($routeProvider){
$routeProvider
.when('/',{controller:ListCtrl,templateUrl:'partials/list.html'})
.when('/edit/:id',{controller:EditCtrl,templateUrl:'partials/details.html'})
.otherwise({redirectTo:'/'})
});
// to map update method
CarApp.factory('CarsService',function($resource){
return $resource('/api/cars/:id',{id:'@_id'} , {update:{method:'PUT'}})
});
function EditCtrl($scope,$location,$routeParams,CarsService){
var id = $routeParams.id;
//console.log(id);
CarsService.get({id: id},function(resp){
$scope.car = resp;
});
// Update Page title
$scope.action = "Update";
$scope.save = function() {
CarsService.update({id:id},$scope.car,function(){
$location.path('/')
});
}
}
这是我的 Express server.js 代码
var express = require('express');
var http = require('http');
var path = require('path');
var cars = require('./server/api/cars.js')
var app = express();
var client_dir = path.join(__dirname, '/client')
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(client_dir));
app.use(express.static(path.join(__dirname, '/image')));
app.get('/', function(req,res){
res.sendfile(path.join(client_dir,'index.html'))
});
// ordering is important to for angularJs to differentiate between list all and read
app.get('/api/cars',cars.list);
app.get('/api/cars/:id',cars.read);
app.post('/api/cars/',cars.create);
app.put('/api/cars/:id',cars.update);
app.del('/api/cars/:id',cars.delete);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
这是我的 details.html 代码
<h2>{{action}} Ferrari</h2>
<form name="carform" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="year">Year</label>
<div class="controls">
<input type="text" ng-model="car.year" id="year" name="year" placeholder="">
</div>
</div>
<div class="form-actions">
<button ng-click="save()" class="btn btn-primary">
Update
</button>
<a href="/" class="btn">Cancel</a>
</div>
</form>
这是我的 mongodb 后端服务
function update(req,res){
var newCarData = req.body;
var id = req.params.id;
newCarData._id = ObjectId(id);
updateCar(newCarData,function(err){
if(err) throw new Error("unable to update");
else{
res.json();
}
});
}
function updateCar(car,callback){
db.collection(collectionName,function(error,collection){
if(error) callback(true);
else {
collection.save(car,function(){
//console.log("updated data") ;
});
}
});
}
我面临的问题是当我按下 details.html 中的更新按钮时,我可以更新我的 mongodb 后端服务中的详细信息。
在控制台中调用了 put 方法,但我无法使用angularJs app.js 文件中的 $location.path('/')重定向到 '/' 路径?任何帮助将不胜感激。