有些我是路由和单页 Web 应用程序的新手,但我一直在努力正确学习 Angular。然而我遇到了一些麻烦和一些奇怪的问题。我遵循了构建目录的指南,我的目录如下所示:
app/
components/
profile/
profile.html
ProfileModel.js
ProfileController.js
ProfileFactory.js
app.module.js
app.routes.js
我的主模块位于 app.module.js
中,并使用 ngRoute
和 profile.app
(配置文件的模块)注入(inject)依赖项从 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
}
所以我有两个主要问题。尽管我在 app.routes.js
中定义了路由,但 $routeParams.user_id
被记录为空。这很奇怪,因为我的 index.html
(包含每个 .js
文件的 HTML 文件)中有一个 ng-view
指令。这意味着一旦 Controller 及其依赖项被实例化,我应该可以立即访问路由参数。但是,当我转到http://example.com/user/1时,我没有记录任何内容(未定义)。
我的第二个问题是我将 ngRoute
作为依赖项包含在 profile.app
和我的主模块中(其中 profile.app
是依赖性)。但是,我后来从 profile.app
中删除了 ngRoute
作为依赖项,但我在 ProfileController< 中留下了
和 AngularJS 根本没有提示。这看起来很奇怪,因为依赖关系不再明确存在于 $routeParams
的注入(inject)profile.app
中。那么为什么我仍然可以注入(inject) $routeParams
尽管我的 profile.app
模块中没有 ngRoute
呢?是因为它从主模块获取ngRoute
吗?
最佳答案
我认为问题在于您将 controllerAs 设置为“profile”
,但随后在 Controller 中编写 var vm = this;
这两个必须相同,以便您可以编写 controllerAs: 'vm'
或 var profile = this;
关于javascript - $routeParams 未填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071927/