Angular是否需要Web服务器才能运行?如果我给浏览器一个本地文件的URL,Angular是否可以工作? [英] Does Angular need a web server to run? So would Angular work if I give browser a url of a local file?
问题描述
通过这个,我的意思是我已经读到Angular允许使用模拟数据,这样就不必连接RESTFul api.我可以想到一个用例,其中UX设计人员只需要查看外观,而无需连接到Web服务器.我也可以想到其他用例.
By this I mean I have read that Angular allows mock up data to be used so that RESTFul apis need not be wired up. I can think of a use case where a UX designer need only look at the cosmetics and need not hook up to a web server. I can think of other use cases as well.
Angular的工作就是我给浏览器一个本地文件的URL,例如C:\ temp \ index.html,而js文件位于c:\ temp或说c:\ temp \ js.
So would Angular work is I give browser a url of a local file like C:\temp\index.html and the js files are either at c:\temp or say c:\temp\js.
所以实际上,我尝试过了,这全部在一个应用程序文件中(我知道应该分开)
So actually, I tried it, here is all in one application file (I know it should be separated)
<html ng-app="myNoteApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-controller="myNoteCtrl">
<h2>My Note</h2>
<p><textarea ng-model="message" cols="40" rows="10"></textarea></p>
<p>
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
</p>
<p>Number of characters left: <span ng-bind="left()"></span></p>
</div>
<script >
// was in separate file but pasted in for demo purposes
var app = angular.module("myNoteApp", []);
</script>
<script >
// was in separate file but pasted in for demo purposes
app.controller("myNoteCtrl", function($scope) {
$scope.message = "";
$scope.left = function() {return 100 - $scope.message.length;};
$scope.clear = function() {$scope.message = "";};
$scope.save = function() {alert("Note Saved:" + $scope.message);};
});
</script>
</body>
</html>
结果是,它可以在Chrome和Firefox中正常运行,IE最初会阻止内容,但是可以允许它运行.
The results are, it works in Chrome and Firefox no problems, IE blocks content initially but one can allow it run.
推荐答案
所以,我这样做的方法是创建一个临时服务,然后仅从URL/文件中加载它.
So, the way I've done this is to create a temp service and just load that instead of from a url/file.
示例:
//tempUser.js
angular.module("app").constant("tempUser", {
firstname : "Joe",
lastname : "Smith"
});
//userService.js
angular.module("app").factory("userService", function ($q, tempUser) {
return {
load : load
};
function load(id) {
//TODO: finish impl
return $q.when(tempUser);
}
});
通过这种方式,控制器仍然可以像从Web服务中加载一样工作.
This way the controller can still work as if you were loading from a web service.
angular.module("app").controller("UserDetailCtrl", function (userService) {
userService.load().then(function (user) {
$scope.user = user;
});
});
这篇关于Angular是否需要Web服务器才能运行?如果我给浏览器一个本地文件的URL,Angular是否可以工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!