将 ngInclude 绑定到不同的模型 [英] Bind ngInclude to different models
问题描述
是否可以为 ngInclude 指定模型,以便在包含的模板内所做的任何更改都反映在指定的模型上.例如:
Is it possible to specify model for ngInclude so that any changes done inside the included template are reflected on the specified model. For instance:
我有一个模型,例如:
$scope.member = {
name: "Member1",
children:[
{
name:"Child1"
},
{
name:"Child2"
}
]
};
和模板:
<script type="text/ng-template" id="name.html">
<input type="text" ng-model="member.name"/>
</script>
现在是否可以通过 ngInclude 成员"或任何子项并修改它们各自的名称属性?我尝试将 ng-model 传递给 ng-template 但它不起作用.我试图用预期的模型动态加载范围,但如果模型被删除,我会留下一个孤立的模板.以下是jsfiddle代码:
Now is it possible to pass ngInclude either "member" or any child and get their respective name properties modified? I tried passing ng-model to the ng-template but it doesn't work. I tried to dynamically load the scope with the intended model but if the model gets delete, I am left with an orphan template. Following is the jsfiddle code:
http://jsfiddle.net/vaibhavgupta007/p7E5K/
我希望重复使用模板而不是为不同的模型复制相同的模板.我已经提到了这个问题:
I wish to reuse the template rather than duplicating the same template for different models. I have refered to this question:
如何在 ngInclude 指令中指定模型AngularJS?
但这里的模型没有被删除.
But here models are not getting deleted.
编辑
到现在为止我还没有掌握创建自定义指令的概念.但是创建一个与 ng-include 结合使用的新指令会有帮助吗?
I have not grasped the concepts of creating custom directives till now. But will creating a new directive in conjuction with ng-include help?
推荐答案
你最后一个问题的答案是:是的.在指令中,您还定义了模板和作用域.范围的内容完全掌握在您的手中.
The answer of your last question is: yes. In a directive, you define also a template and a scope. The content of the scope is completely in your hands.
见这里:http://jsfiddle.net/vgWQG/1/
用法:
Member: <member model="member"></member>
<ul>
<li ng-repeat="child in member.children">
Child {{$index}}: <member model="child"></member>
</li>
</ul>
指令:
app.directive('member', function(){
return {
template : '<input type="text" ng-model="member.name"/>',
replace : true,
restrict: 'E',
scope : {
'member' : '=model'
},
link: function(scope, element, attr) {}
};
});
我已经将模板移到了内联变体中,因为我无法让模板缓存在 jsfiddle 中工作.在现实世界中,templateUrl: 'name.html' 应该没问题.
I've moved the template in an inline variant because I could not getting the template cache getting to work in jsfiddle. In a real world, a templateUrl: 'name.html' should be fine.
这就是你想要的?
这篇关于将 ngInclude 绑定到不同的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!