我刚刚在名为helloWorldz.js
的文件中创建了一个如下所示的指令:
'use strict';
angular.module('components')
.directive('helloWorld', function () {
return {
restrict : 'E',
template : '<span>Hello World</span>'
};
});
我的app.js
文件,其中包含我的路线,如下所示:
'use strict';
angular.module('mmApp', ['components'])
.config(function ($routeProvider) {
$routeProvider
.when('/designs', {
templateUrl: 'views/designs.html',
controller: 'MainCtrl'
})
.when('/blog', {
templateUrl: 'views/blog.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
我未完成的控制器main.js
看起来像这样:
'use strict';
angular.module('mmApp', [])
.controller('MainCtrl', function ($scope) {
$scope.designTiles = [
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
];
});
Chrome开发工具告诉我helloWorldz.js
正在成功加载。见下文
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9mS01VbS5wbmcifQ==” alt =“在此处输入图像描述”>
[我应该提一下,如果将指令代码放在控制器后的main.js
中,并在['components']
之后将mmApp
作为参数传递,我将看到指令代码有效。这是更改后的main.js
控制器:
'use strict';
angular.module('mmApp', ['components'])
.controller('MainCtrl', function ($scope) {
$scope.designTiles = [
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
{ imageURL : "", title : "IMAGE" },
];
});
angular.module('components', [])
.directive('helloWorld', function () {
return {
restrict : 'E',
template : '<span>Hello World</span>'
}
});
为什么app.js
无法在包含我的components
指令的helloWorld
模块中成功调用? app.js
无法连接到helloWorldz.js
,这是否可能是问题?
我还应该提到,我正在使用grunt编译所有内容。
看起来该指令代码在独立版本中略有不同。有:
angular.module('components')
而不是
angular.module('components',[])
解决了该问题(通过将参数添加到独立版本中)可以解决此问题。我认为很多人都遇到了这个问题,因为对AngularJS's module page的最高评价是:
此文档应警告“ angular.module('myModule',[])”总是创建一个新模块,但是总是“ angular.module('myModule')”检索现有参考。