this vs $scope in angular.js?

This question already has an answer here:

  • 'this' vs $scope in AngularJS controllers 7 answers

  • The function you put into angular.controller is used as a constructor. JavaScript constructors that return nothing, implicitly return this . If a constructor returns another object, then this object is supposed to be the new object. eg:

    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'
    

    Your controller returns an http promise (the return value of $http.get(...).success(...) ), so angular believes that this (the http promise) is your actual controller (the thing it assigns to $scope.labCtrl ).

    No time to test it, hope I got it right.

    Tiny example here


    You assigned a value to this.laboratorios inside a closure. Remember that its scope is separated from the outer scope. this applies to something completely different. This is why using $scope is more reliable (and readable, if you ask my personal opinion). You might want to bind the closure to a this value:

    (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));
        });
    })();
    

    Alternatively, you can use a variable that will be available from both scopes:

    (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;
          });
        });
    })();
    
    链接地址: http://www.djcxy.com/p/77792.html

    上一篇: 这两个Angular代码片段有什么区别?

    下一篇: 这与angular.js中的$ scope有关吗?