我正在使用typescript构建一个angularjs应用程序,并刚刚创建了我的第一个控制器 - 问题是我很难将ng-model
与其上的对象一起使用。
这就是它的样子;
app.ts
((): void => {
'use strict';
angular.module('app', ['app.core','app.widgets','app.services']);
})();
app.services.ts
此处定义了用户服务,与此示例无关
“app.widgets.ts`
module app.widgets {
'use strict';
interface IUserController {
User: app.services.IUser;
}
class UserController implements IUserController {
User: app.services.IUser;
static $inject = ['$scope', 'app.services.UserService'];
constructor(scope: any, userService: app.services.IUserService){
var vm = this;
userService.Find().then((user: app.services.IUser): void => {
scope.User = user; // this is the offending line
});
}
}
angular.module('app.widgets').controller('app.widgets.UserController', UserController);
}
我尝试在我的HTML中调用它;
<body ng-app="app" ng-controller="app.widgets.UserController">
{{ User.UserName }}
</body>
或.. ..
<h1 ng-model="User.UserName"></h1>
我还没有完全解决它,但我取得了更多进展
interface IUserControllerScope extends angular.IScope {
User: app.services.IUser;
}
class UserController {
static $inject = ['$scope', 'app.services.UserService'];
constructor($scope: IUserControllerScope, userService: app.services.IUserService) {
var _this = $scope;
userService.Find().then((user: app.services.IUser): void => {
_this.User = user;
});
}
}
}
答案 0 :(得分:1)
我认为问题是因为scope
未定义。尝试将scope
更改为$scope
。然后你可以像这样访问用户
$scope.User = user
答案 1 :(得分:1)
{{User.UserName}}
这行可能有拼写错误。尝试
<pre> {{User | json}} </pre>
我怀疑它应该是User.username
答案 2 :(得分:1)
class UserController implements IUserController {
User: app.services.IUser;
public user:any;
static $inject = ['$scope', 'app.services.UserService'];
constructor(scope: any, userService: app.services.IUserService){
userService.Find().then((user: app.services.IUser): void => {
this.User = user; // this is the offending line
});
//assign instance to a scope variable and access in view
scope.vm=this
}
}
angular.module('app.widgets').controller('app.widgets.UserController', UserController);
}
在视图中
<div>{{vm.user}}</div>