【发布时间】:2014-12-02 18:14:38
【问题描述】:
刚开始了解 Angular - 由于我来自 Backbone 学派,因此无法理解一些概念。
我随机选择了一个项目开始:纸牌游戏。
假设我想定义一个hand 控制器和一个card 控制器。为简单起见,我希望将它们作为指令。
这是卡片指令:
app.directive('card', function(){
return {
restrict:'E',
templateUrl:'card.html',
controller:function($scope){
this.suit = 'clubs';
this.rank = 'a';
this.suitClass = function(){
return this.suit + '-' + this.rank;
}
},
controllerAs:'card'
};
});
这里是手动指令:
app.directive('hand', function(){
return {
restrict:'E',
template:'hand.html',
controller:function($scope){
this.cards = [
{suit:'clubs', rank:'a'},
{suit:'spades', rank:'10'},
{suit:'hearts', rank:'2'},
{suit:'diamonds', rank:'k'}
];
},
controllerAs:'hand'
}
});
使用following plunker,我希望能够简单地放入<hand></hand> 元素并让angular 为我完成所有工作。在我看来,<hand> 指令中应该有代表不同花色的卡片。我错过了什么?目前,正如您在 plunker 中看到的那样,嵌套的控制器/指令无法正确实例化视图。
我是否以 MVC 方式思考太多? OOP 困扰着我吗?还是 Angular 的设计很糟糕?
【问题讨论】:
-
Forked your plunker 进行了一些小的更改,来自 controllerAs 的“card”和来自 repeat 的“card”在那个范围内有点崩溃了。它远非完美的解决方案,但希望尽可能少地进行更改,以便您了解如何设置它来工作。
-
@JimL 感谢您的支持。那么我是否正确假设两个视图之间没有真正的关系,接受来自
hand的属性通过$scope命名空间组合添加到新的card中?
标签: javascript angularjs angularjs-directive angularjs-ng-repeat