Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在控制器中使用此选项的正确方法_Angularjs - Fatal编程技术网

Angularjs 在控制器中使用此选项的正确方法

Angularjs 在控制器中使用此选项的正确方法,angularjs,Angularjs,我在一篇博客中听说,准备Angular 2.0的一个简单方法是不要在控制器中使用$scope,而是使用this。我发现在控制器内部的函数中使用的this不是this,它应该是$scope 失败 var loginControllerId = 'loginCtrl'; app.controller(loginControllerId, ['$scope',function ($scope) { this.login = {}; function myFunc(){

我在一篇博客中听说,准备Angular 2.0的一个简单方法是不要在控制器中使用$scope,而是使用this。我发现在控制器内部的函数中使用的this不是this,它应该是$scope

失败

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() {

    }
  });
}
请看这篇文章的完整解释

看看这个