【发布时间】:2016-01-24 22:45:34
【问题描述】:
我刚刚开始使用 AngularJS 开发一个应用程序
当我定义我的控制器时,我注意到一些奇怪的事情,我自己似乎无法回答。
我的控制器:
(function () {
"use strict";
angular
.module("app")
.controller("LaunchController", LaunchController);
LaunchController.$inject =["User"];
function LaunchController() {
var vm = this; //this = controllerobject -- vm(=ViewModel)
vm.name = "launchtestname";
vm.user= new User("a","b","c","d","e");
}
;
})()
以及我正在调用的服务:
(function () {
"use strict";
angular
.module("app")
.factory("User", User);
function User() {
/**
* Constructor, with class name
*/
var User =function (firstName, lastName, role, organisation) {
// Public properties, assigned to the instance ('this')
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
this.organisation = organisation;
}
/**
* Public method, assigned to prototype
*/
User.prototype.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
/**
* Private property
*/
var possibleRoles = ['admin', 'editor', 'guest'];
/**
* Private function
*/
function checkRole(role) {
return possibleRoles.indexOf(role) !== -1;
}
/**
* Static property
* Using copy to prevent modifications to private property
*/
User.possibleRoles = angular.copy(possibleRoles);
/**
* Static method, assigned to class
* Instance ('this') is not available in static context
*/
User.build = function (data) {
if (!checkRole(data.role)) {
return;
}
return new User(
data.first_name,
data.last_name,
data.role,
Organisation.build(data.organisation) // another model
);
};
/**
* Return the constructor function
*/
console.log(User);
return User;
};
})();
现在,当我在启动控制器中调用用户构造函数时遇到的问题是,我收到了未定义用户的错误。
但是,如果我像这样将我的用户服务注入控制器:
function LaunchController(User) {
没有 $inject - 问题不会发生。
我想知道这两个调用之间有什么区别,因为我想使用 gulp 来缩小我的代码并且不丢失对 User 的引用(我在 $inject 中使用文字)
【问题讨论】:
标签: angularjs dependency-injection