Angularjs 在控制器中使用此选项的正确方法
我在一篇博客中听说,准备Angular 2.0的一个简单方法是不要在控制器中使用$scope,而是使用this。我发现在控制器内部的函数中使用的this不是this,它应该是$scope 失败Angularjs 在控制器中使用此选项的正确方法,angularjs,Angularjs,我在一篇博客中听说,准备Angular 2.0的一个简单方法是不要在控制器中使用$scope,而是使用this。我发现在控制器内部的函数中使用的this不是this,它应该是$scope 失败 var loginControllerId = 'loginCtrl'; app.controller(loginControllerId, ['$scope',function ($scope) { this.login = {}; function myFunc(){
var loginControllerId = 'loginCtrl';
app.controller(loginControllerId, ['$scope',function ($scope) {
this.login = {};
function myFunc(){
// FAILS - this.login is undefined I think because "this" is now referring to the myFunc function
this.login.message = "Some Message";
}
this.login.successMessage = "Success"; // PASSES
});
var loginControllerId = 'loginCtrl';
app.controller(loginControllerId, ['$scope',function ($scope) {
var loginScope = this;
loginScope.login = {};
function myFunc(){
// PASSES
loginScope.login.message = "Some Message";
}
loginScope.login.successMessage = "Success"; // PASSES
});
我认为解决方法是创建一个var,并将这个($scope)设置为它。有人能告诉我这是一种很好的方法吗?或者是否有一种不同的方法来全局使用控制器this
通过
var loginControllerId = 'loginCtrl';
app.controller(loginControllerId, ['$scope',function ($scope) {
this.login = {};
function myFunc(){
// FAILS - this.login is undefined I think because "this" is now referring to the myFunc function
this.login.message = "Some Message";
}
this.login.successMessage = "Success"; // PASSES
});
var loginControllerId = 'loginCtrl';
app.controller(loginControllerId, ['$scope',function ($scope) {
var loginScope = this;
loginScope.login = {};
function myFunc(){
// PASSES
loginScope.login.message = "Some Message";
}
loginScope.login.successMessage = "Success"; // PASSES
});
通常使用
var vm=this代码>在控制器中。查看非常流行的。通常使用var vm=this代码>在控制器中。查看非常流行的。另一种方法是使用角度延伸
function MainCtrl () {
angular.extend(this, {
someVar: {
name: 'Todd'
},
anotherVar: [],
doSomething: function doSomething() {
}
});
}
请看这篇文章的完整解释
另一种方法是使用角度延伸
function MainCtrl () {
angular.extend(this, {
someVar: {
name: 'Todd'
},
anotherVar: [],
doSomething: function doSomething() {
}
});
}
请看这篇文章的完整解释
看看这个