簡體   English   中英

使用“ controller as”語法時,如何訪問控制器中的“ this”?

[英]How can I access the “this” in my controller when using “the controller as” syntax?

我有以下代碼:

var app = angular.module('plunker', []);

app.controller('ParentCtrl', function($scope) {
  $scope.name1 = 'Parent';
  this.name1 = 'Parent';
});

app.controller('ChildCtrl', function($scope) {
  $scope.name1 = 'Child';
  this.name1 = 'Child';
  this.option = {};
  this.option.abc = 25;

  foo = function(){
    alert(this.option)
  };

  foo();
});

當我嘗試使用該功能之前的“ this”時。 當我嘗試在函數內部訪問this時,它是未定義的。 有人可以告訴我是否有一種“ AngularJS”方法可以解決此問題?

如果您使用Controller As Syntax,則聲明如下:

$scope.name1 = 'Child';
this.name1 = 'Child'; 

是多余的。 當您指定'As'角時,它將在此定義的所有屬性上復制到$ scope變量。

至於為什么this在您的功能中不起作用。 this關鍵字是指函數的執行上下文。 正如您已經聲明的那樣,沒有上下文。 為了得到this是你希望它是什么,你可以這樣做:

this.foo = function(){...this is this...}

或者如果您不想在示波器上顯示它。 您可以使用模塊顯示模式。

var self = this;
function foo(){...self is 'this'...};

您需要在函數開始時保留對它的引用並使用它。 的情況下this我相信在您的函數是全局窗口。 這完全取決於函數的調用方式以及在何處定義。

app.controller('ChildCtrl', function($scope) {
  var self=this;
  $scope.name1 = 'Child';
  this.name1 = 'Child';
  this.option = {};
  this.option.abc = 25;

  foo = function(){
    alert(self.option)
  };

  foo();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM