昨天,我看到我的同事寫了一個巨大的控制器,只有一個「上帝對象」$scope
應該看起來像下面的代碼。
myApp.controller('ComplexController', ['$scope', function($scope) {
$scope.firstTab = {
init: function() {
$scope.firstTab.data1.foo = $scope.firstTab.DefaultData1.foo;
$scope.$watch('firstTab.data1.foo', function(){
// do something
});
},
defaultData1: {
foo: 'bar'
},
data1: {
foo: 'bar',
publiclyUsedMethod1: function() {},
publiclyUsedMethod2: function() {},
privatelyUsedMethod1: function() {},
privatelyUsedMethod2: function() {},
privatelyUsedMethod3: function() {},
privatelyUsedMethod4: function() {},
privatelyUsedMethod5: function() {}
},
data2: {
// Same code pattern as above
},
data3: {
// Same code pattern as above
},
data4: {
// Same code pattern as above
}
};
$scope.secondTab = {
// Same code pattern as above
};
$scope.thirdTab = {
// Same code pattern as above
};
$scope.refresh = function(){
// do something
};
$scope.$watchCollection('[$scope.firstTab.data1.foo, $scope.secondTab.data1.foo, $scope.thirdTab.data1.foo]',function(newValues,oldValues){
// some logic
$scope.refresh();
});
$scope.firstTab.init();
$scope.secondTab.init();
$scope.thirdTab.init();
}]);
您認爲哪種模式? $scope
對象的主要用途是什麼?可以將每個私人和公共對象存儲在$scope
對象中嗎?
謝謝,
可能的重複[在AngularJS中範圍原型/原型繼承的細微差別?](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical- inheritance-in-angularjs) –
$ scope是這個angularjs黑盒子的句柄。 – harrrrrrry
無需將私人方法放在範圍上。將它們推送到可在任何地方使用的服務 – charlietfl