当我在本地机器上运行这段代码时,我无法得到它的输出,但奇怪的是在线编辑器能够给我一个输出:http://codepen.io/anon/pen/waXGom
*我正在使用 Adobe Brackets 编辑器
这是我的 HTML 代码:
<!DOCTYPE html >
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src= "app.js"></script>
<body ng-app="MyApp">
<div ng-controller="Controller2">
<button ng-click="add()">Add Object</button>
<button ng-click="reset()">Reset</button>
<div remove="remove($index)" ng-repeat="name in names">
{{name}}
</div>
</div>
</body>
</html>
这是我的 JS 代码:
var myApp = angular.module('myApp', []);
myApp.controller('Controller2', function ($scope) {
$scope.names = [];
var data = ['Dean', 'Andy', 'Dan', 'Wizek', 'Pete', 'Pawel', 'Chris', 'Misko'];
$scope.add = function() {
if (data.length)
$scope.names.push(data.pop());
};
$scope.reset = function(index) {
data.push($scope.names.splice(index, 1)[0]);
};
});
请帮我弄清楚...
最佳答案
您的意思是您看到了来自 JSLint 的 angular used before it was defined 错误?那是因为您在 JavaScript 代码中使用了全局的 angular
而没有让 JSLint 首先知道它在范围内。
JSLint 在逐页级别上运行,无法从外部包含的内容中分辨出全局上下文中的内容。您已经在另一个包含中将 Angular 加载到全局上下文中,但是当 JSLint 自己查看这个单个 JavaScript 文件时,它无法分辨出这一点。
要明确一点,仅仅这一行就应该已经导致 JSLint 报告错误:
var myApp = angular.module('myApp', []);
你必须添加一个 global
指令让 JSLint 知道全局上下文中有什么。
/*global angular */
var myApp = angular.module('myApp', []);
现在你是金色的。
只是为了好玩,这里有一个完整的 JSLinted JavaScript 文件片段的版本。没用多少。请注意,我必须在您的 if
block 和 jslint 指令 white:true
周围添加波浪形括号,因为它认为是非标准空白。更多信息 here .
/*jslint white:true */
/*global angular */
var myApp = angular.module('myApp', []);
myApp.controller('Controller2', function ($scope) {
"use strict";
$scope.names = [];
var data = ['Dean', 'Andy', 'Dan', 'Wizek', 'Pete', 'Pawel', 'Chris', 'Misko'];
$scope.add = function() {
if (data.length)
{
$scope.names.push(data.pop());
}
};
$scope.reset = function(index) {
data.push($scope.names.splice(index, 1)[0]);
};
});
关于javascript - 错误 : "angular was used before it was defined" but online editors able to output the result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31390428/