Angularjs angular.js教程的第2级
我刚刚在level 2的angular.js教程中看到了这一点:Angularjs angular.js教程的第2级,angularjs,Angularjs,我刚刚在level 2的angular.js教程中看到了这一点: (function() { var app = angular.module('gemStore', []); app.controller('StoreController', function(){ this.products = gems; }); app.controller("TabController", function(){ this.tab = 1; this.set
(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函数如何改变tabcontroller的tab变量的值?如果我在setTab函数中使用'this.tab',setTab函数将只是给它自己的内部作用域分配一个变量,不是吗?你必须看看angular如何在内部调用函数-它使用
app.controller("TabController").setTab.apply($scope, [selectedTab])
它调用setTab
函数,但将this
的值设置为$scope
对象
比这复杂一点,但这就是“如何”
一般来说,我更喜欢在我的控制器中使用$scope
对象,因为它是这样的,感觉不那么“神奇”
关于更多信息,这个问题很好地解释了这一点:
要了解fn.apply
的工作原理,下面是一个简单的示例:
x = function() { alert(this.test); }
x(); //alerts "undefined"
x.apply({test: 'hello!'}); //alerts "hello!"
如果我在setTab函数中使用'this.tab',setTab函数将
只是把一个变量赋给它自己的内部作用域,不是吗
事实上,没有
此
,在您的setTab
函数中是对TabController
的某些特定实例的引用。因此,this.tab
表示“TabController实例的tab属性”。这个实例将由Angular Internal创建以处理视图,所以您不必担心这个部分
编辑:
您可以使用以下示例:
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方法。:@我不喜欢这样。我很困惑,这让人困惑。为了使用angular,我需要强迫自己忘记一些javascript基础知识。js@andre,这是一个JavaScript基础,不是一个角度的东西。
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