我刚刚开始学习 MVC 和 Angular,我对以下代码感到好奇(摘自 angularjs.org)
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="Scripts/Todo.js" type="text/javascript"></script>
<link rel="stylesheet" href="todo.css">
</head>
<body>
<h2>
Todo</h2>
<div ng-controller="TodoCtrl">
<span>{{remaining()}} of {{todos.length}} remaining</span> [ <a href="" ng-click="archive()">
archive</a> ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span> </li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30" placeholder="">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</body>
Todo.js
function TodoCtrl($scope) {
$scope.todos = [
{ text: 'learn angular', done: true },
{ text: 'build an angular app', done: false}];
$scope.addTodo = function () {
$scope.todos.push({ text: $scope.todoText, done: false });
$scope.todoText = '';
};
$scope.remaining = function () {
var count = 0;
angular.forEach($scope.todos, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.archive = function () {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function (todo) {
if (!todo.done) $scope.todos.push(todo);
});
};
}
如果不引人注目的 javascript 的原则说我们需要将行为与表示分离,那么为什么 Angular 拥有像 ng-click=archive()
这样的代码是可以的,也是最佳实践?
最佳答案
不引人注目的 javascript 是一个较旧的概念,其重要性已不如以前。来自 Wikipedia ,
Adherents to "Unobtrusive JavaScript" argue that the purpose of markup is to describe a document's structure, not its programmatic behavior and that combining the two negatively impacts a site's maintainability.
可用性并不相关,因为除了您的开发团队之外没有人查看您的 DOM 代码。一旦您接受了 Angular 哲学,内联事件处理程序就更容易维护。不过,您始终可以使用 $watch保持您的 HTML 简洁。
正如 Angular 网站所说,
AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.
搜索引擎对您的网站建立索引可能会稍微困难一些,但我们有 RSS、站点地图和 AJAX Crawling来解决这个问题。
优雅降级不再相关,除非您为非智能手机市场构建应用程序。几乎所有用户都使用支持现代 JavaScript(带有填充程序)的浏览器。
辅助功能和 Angular 并不冲突。只需确保使用 ARIA 标签和正确的标记即可。 Angular 使编写可测试代码变得更加容易,并且内置了 exception handling 。
关注点分离如果您使用函数污染了全局范围,那么关注点分离就是一个问题。 Angular 可以更轻松地单独维护 JavaScript 代码,而不会影响其他文件或代码。
关于javascript - Angular JS 和不显眼的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906804/