有些我是新的路由和单页网页应用程序,但我一直在努力学习角正确。不过,我遇到了一些麻烦,还有一些奇怪的问题。我遵循了关于构造目录的指南,我的指南如下所示:
app/
components/
profile/
profile.html
ProfileModel.js
ProfileController.js
ProfileFactory.js
app.module.js
app.routes.js我的主要模块位于app.module.js中,依赖注入了ngRoute和profile.app (来自ProfileModel.js的概要视图模块)。声明如下:
angular
.module('app', ['ngRoute', 'profile.app'])
.controller('MainController', MainController);
function MainController() {
this.message = 'This is the home page';
}然后,在我的app.routes.js文件中,我声明了应用程序需要的所有路由(到目前为止只有一个,即概要文件):
angular
.module('app')
.config(routeConfig);
routeConfig.$inject = ['$locationProvider', '$routeProvider'];
function routeConfig ($locationProvider, $routeProvider) {
$routeProvider
.when('/user/:user_id', {
templateUrl: '/app/components/profile/profile.html',
controller: 'ProfileController',
controllerAs: 'profile'
}
)
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}这是我的ProfileController.js
angular
.module('app.profile')
.controller('ProfileController', ProfileController);
ProfileController.$inject = ['ProfileFactory', '$routeParams'];
function ProfileController(ProfileFactory, $routeParams) {
var vm = this;
vm.user_id = $routeParams.user;
console.log($routeParams.user_id);
vm = ProfileFactory.userProfile(vm.user_id); //Gets the profile of the user and sets to to vm
}所以我有两个主要问题。尽管我已经在$routeParams.user_id中定义了路由,但它还是被记录为没有记录。这很奇怪,因为我的index.html中有一个index.html指令(包含每个.js文件的HTML )。这意味着,一旦控制器及其依赖项被实例化,我应该可以立即访问路由参数。但是,当我进入http://example.com/user/1时,没有任何记录(未定义)。
我的第二个问题是,我将ngRoute作为一个依赖项包含在profile.app和我的主模块中(其中profile.app是一个依赖项)。但是,后来我将ngRoute从profile.app中删除为依赖项,但是我将$routeParams注入到了ProfileController中,而AngularJS完全没有抱怨。这似乎很奇怪,因为依赖关系不再显式地存在于profile.app中。那么,尽管我的$routeParams模块中没有ngRoute,但为什么我仍然可以注入profile.app呢?是因为它从主模块获得ngRoute吗?
发布于 2015-10-12 01:38:11
我相信问题在于您正在设置controllerAs to 'profile',但是在控制器中编写var vm = this;
这两者必须是相同的,这样才能编写controllerAs: 'vm'或var profile = this;。
https://stackoverflow.com/questions/33071927
复制相似问题