【发布时间】:2013-05-15 05:12:08
【问题描述】:
对于范围有限的指令,我很难理解模型的范围及其绑定。
我知道限制指令的范围意味着 controller.$scope 和directive.scope 不再是同一个东西。但是,我对在指令模板或 html 中放置模型如何影响数据绑定感到困惑。我觉得我错过了一些非常基本的东西,要继续前进,我需要了解这一点。
获取以下代码(此处为小提琴:http://jsfiddle.net/2ams6/)
JavaScript
var app = angular.module('app',[]);
app.controller('Ctrl',function($scope){
});
app.directive('testel', function(){
return {
restrict: 'E',
scope: {
title: '@'
},
transclude: true,
template: '<div ng-transclude>'+
'<h3>Template title: {{title}}</h3>' +
'<h3>Template data.title:{{data.title}}</h3>' +
'</div>'
}
});
HTML
<div ng-app='app'>
<div ng-controller="Ctrl">
<input ng-model="data.title">
<testel title="{{data.title}}">
<h3>Transclude title:{{title}}</span></h3>
<h3>Transclude data.title:{{data.title}}</h3>
</testel>
</div>
</div>
模型仅在模板内更新{{title}},在嵌入中更新{{data.title}}。 为什么不是{{title}} 在嵌入中,也不是{{data.title}} 在模板中?
像这样将输入移动到嵌入中(这里小提琴:http://jsfiddle.net/eV8q8/1/):
<div ng-controller="Ctrl">
<testel title="{{data.title}}">
<input ng-model="data.title">
<h3>Transclude title: <span style="color:red">{{title}}</span></h3>
<h3>Transclude data.title: <span style="color:red">{{data.title}}</span></h3>
</testel>
</div>
现在意味着只有 transclude {{data:title}} 被更新。 为什么不使用{{title}} 或{{data.title}} 模板,也不要转换{{title}}?
最后,将输入移动到模板中,就像这样(在这里摆弄:http://jsfiddle.net/4ngmf/2/):
template: '<div ng-transclude>' +
'<input ng-model="data.title" />' +
'<h3>Template title: {{title}}</h3>' +
'<h3>Template data.title: {{data.title}}</h3>' +
'</div>'
现在意味着只有模板{{data.title}} 得到更新。 再说一遍,为什么不是其他 3 个绑定?
我希望有什么明显的东西在盯着我看,但我很想念它。如果你让我得到这个,我会给你买啤酒,或者给你一些积分,或者其他类似的东西。非常感谢。
【问题讨论】:
-
这是一个很大的话题,很遗憾在开始工作之前我没有时间提供太多细节,但请阅读 Mark Rajcok 的 Scope/Prototypal Inheritance Guide。有很多图表,这很有帮助,他涵盖了嵌入。
-
@BrandonTilley 惊人的文章。非常感谢您发布它。只是努力解决它。周二可以花更多的时间。
标签: angularjs angularjs-directive angularjs-scope