【问题标题】:this vs $scope in angular.js? [duplicate]这与 angular.js 中的 $scope 对比? [复制]
【发布时间】:2014-06-04 14:32:49
【问题描述】:

我正在使用 Angular 开发一个 Rails 应用程序,过去,我一直使用 $scope 来访问 Angular 控制器的变量和方法。 看了 codeschool 的 Shaping up with Angular.js 课程后,我意识到 this 的使用和控制器的别名是访问它们的更好方法。

无论如何,我的应用在 $scope 上运行良好,但是当我更改为“this”实现时,laboratory var 变空了...

我在这里放了一些代码: html:

<div ng-controller="LaboratorioController as labCtrl">
          <tr ng-repeat="laboratorio in labCtrl.laboratorios" >
            <td>{{ laboratorio.nombre }}</td>
            <td>{{ laboratorio.razon_social }}</td>
            <td>{{ laboratorio.direccion }}</td>

角码:

(function() {
    var app = angular.module('guiaV', []);
    app.controller('LaboratorioController', function( $http) {
      this.laboratorios = [];
      return $http.get('./laboratorios.json').success(function(data) {
        return this.laboratorios = data;
      });
    });
})();

有什么想法吗?

【问题讨论】:

  • @Blackhole 我已经看到了那个答案,但对我没有帮助......
  • 所以这里有一个很好的提示:使用$scope。真的。
  • stackoverflow.com/questions/11605917/… 有类似的问题“标题”并不一定是重复的......快速审阅者也应该阅读内容。

标签: javascript ruby-on-rails angularjs


【解决方案1】:

您放入angular.controller 的函数用作构造函数。不返回任何内容的 JavaScript 构造函数隐式返回 this。如果构造函数返回另一个对象,则该对象应该是新对象。例如:

function Class1() {
    this.prop = 'xxx';
}
var obj1 = new Class1();
console.log(obj1.prop); // prints 'xxx'

function Class2() {
    this.prop = 'xxx';
    return {
        hooray: 'yyy'
    };
}
var obj2 = new Class2();
console.log(obj2.prop); // prints undefined
console.log(obj2.hooray); // prints 'yyy'

您的控制器返回一个 http 承诺($http.get(...).success(...) 的返回值),因此 Angular 认为这(http 承诺)是您的实际控制器(它分配给 $scope.labCtrl 的东西)。

没时间测试,希望我做对了。

小例子here

【讨论】:

    【解决方案2】:

    您在闭包内为this.laboratorios 分配了一个值。请记住,它的作用域与外部作用域是分开的。 this 适用于完全不同的东西。这就是为什么使用$scope 更可靠(如果你问我个人意见,也更易读)。您可能希望将闭包绑定到 this 值:

    (function() {
        var app = angular.module('guiaV', []);
        app.controller('LaboratorioController', function( $http) {
          this.laboratorios = [];
          $http.get('./laboratorios.json').success(function(data) {
            return this.laboratorios = data;
          }.bind(this));
        });
    })();
    

    或者,您可以使用在两个范围内都可用的变量:

    (function() {
        var app = angular.module('guiaV', []);
        app.controller('LaboratorioController', function( $http) {
          this.laboratorios = [];
          var foo = this;
          $http.get('./laboratorios.json').success(function(data) {
            return foo.laboratorios = data;
          });
        });
    })();
    

    【讨论】:

    • Really no。在控制器内部,this 不是 $scope
    • @Blackhole 你没有帮助。真的。
    • @nilsK 什么不清楚? this不是$scope,详细解释在链接里。
    • 您决定对我的答案投反对票,在 cmets 中挑剔,并大声疾呼答案是骗人的,而不是仅仅指出完整的答案。我决定尽我所能提供帮助。
    • Blackhole 我们是stackoverflow 的一部分来帮助其他开发者,如果您不想这样做,请删除您的帐户。谢谢@mingos,这就是开发者社区所寻求的态度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    相关资源
    最近更新 更多