这是我第一次尝试创建一个示例angular应用程序。在app.js
中,我定义了以下内容-
var app = angular.module('myTestApp', ['ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch']);
app.config(function ($routeProvider) {
routeProvider
.when('sample', {
templateUrl: 'views/sample.html',
controller: 'sampleCtrl'
})
});
我已经为控制器创建了相应的sample.js
,为模板创建了sample.html
,为模型创建了对应的sampleModel.js
。在grunt控制台中,它抛出控制器和模型文件中未定义的app
这是控制器文件-
'use strict';
app.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
所有的文件都包含在index.html中,资源加载正确,我通过chrome开发工具检查了这一点,但我找不到为什么它说应用程序没有定义。我缺什么了吗?
由于它们是单独的文件,grunt/jshint不会知道该变量在其他文件中可用。相反,以这种方式使用它将是一种最佳实践:
相反,使用这个:
angular.module('myTestApp')
.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
您可能在大多数其他代码中注意到的另一种通用模式是将代码封装在IIFE中。
(function() {
"use strict";
var app = angular.module('myTestApp')
app.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
})();
在这个应用程序中,它不会污染全局名称空间,并且它是该函数的本地名称空间。
在这里,如果你注意到,我在使用angular.module()
时没有使用[]
,这意味着我们只是得到了那个模块。
在你的应用程序中也是如此s,它将与[]
一起使用,而在其他没有[]
的文件中
(function() {
"use strict";
var app = angular.module('myTestApp', ['ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch']);
app.config(function ($routeProvider) {
$routeProvider
.when('sample', {
templateUrl: 'views/sample.html',
controller: 'sampleCtrl'
})
});
})();
如果其他一切都很好,这一行会导致代码中的问题-
app.config(function ($routeProvider) {
routeProvider
你应该改为使用-
app.config(function ($routeProvider) {
$routeProvider
是的,如果var app
不工作,请尝试使用
angular.module('myTestApp')
.controller('SampleCtrl',...