在 Angular.js 中,this 和 $scope 有什么不同?
在 Angular.js 中,this 和 $scope 有什么不同?
这个问题已经在这里有了答案:
我正在用angular开发rails应用程序,在过去,我一直使用 $scope 来访问angular控制器的变量和方法。在观看了 codeschool 的 Shaping up with Angular.js 课程后,我意识到使用 this 和控制器别名是访问它们的更好方式。
无论如何,我的应用程序在使用 $scope 时工作正常,但当我改成使用\"this\"实现时,实验室变量却为空...。
我在这里留下一些代码:
{{ laboratorio.nombre }}
{{ laboratorio.razon_social }}
{{ laboratorio.direccion }}
angular 代码:
(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; }); }); })();
有什么想法吗?
admin 更改状态以发布 2023年5月20日
你在闭包中给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; }); }); })();
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 promise($http.get(...).success(...)
的返回值),因此angular认为这个http promise就是您实际的控制器(分配给$scope.labCtrl
的东西)。
没有时间测试它,希望我理解正确。
这里有一个小例子(点击这里)