我刚刚在第2级的angular.js教程中看到了这一点:
(function() {
var app = angular.module('gemStore', []);
app.controller('StoreController', function(){
this.products = gems;
});
app.controller("TabController", function(){
this.tab = 1;
this.setTab = function(selectedTab){
this.tab = selectedTab;
};
});
var gems = [// a lot of code here...]
})();
我的疑问是: setTab函数如何改变TabControler选项卡变量的值?如果我在this.tab函数中使用‘setTab’,setTab函数将只是将一个变量赋值给它自己的内部作用域,不是吗?
发布于 2014-10-15 16:56:22
如果我在this.tab函数中使用‘setTab’,setTab函数将只是将一个变量赋值给它自己的内部作用域,不是吗?
实际上,不是。
this
,在您的setTab
函数中是一个引用--某个特定的TabController
实例。因此,this.tab
的意思是“TabController实例的选项卡属性”。这个实例将由角度内部创建来处理视图,所以您就不用担心这个部分了。
编辑:
您可以使用此示例:
var MyConstructor = function() {
this.tab = 0;
this.setTab = function(newTab) {
this.tab = newTab;
};
this.logTab = function() {
console.log(this.tab);
};
};
var myObj = new MyConstructor();
myObj.logTab(); // prints 0
myObj.setTab(2);
myObj.logTab(); // prints 2
但是,正如dave提到的,我会坚持$scope方法。
发布于 2014-10-15 16:41:01
你必须看看角形如何在内部调用这个函数--它使用的方法如下
app.controller("TabController").setTab.apply($scope, [selectedTab])
它调用setTab
函数,但将this
的值设置为$scope
对象。
这比这要复杂一些,但这就是“怎么做”。
一般来说,我更喜欢在控制器中使用$scope
对象,因为它确实存在,而且感觉上没有那么“神奇”。
app.controller("TabController", function($scope){
$scope.tab = 1;
$scope.setTab = function(selectedTab){
$scope.tab = selectedTab;
};
});
关于更多的信息,这个问题解释得很好:'this' vs $scope in AngularJS controllers
为了了解fn.apply
是如何工作的,下面是一个简单的示例:
x = function() { alert(this.test); }
x(); //alerts "undefined"
x.apply({test: 'hello!'}); //alerts "hello!"
https://stackoverflow.com/questions/26387599
复制相似问题