伙计我有一些简单的HTML,为了说明目的,它看起来像这样,
<div>{{class.name}}</div>
<div>
<div>{{class.teacher.name}}</div>
<div>{{class.teacher.age}}</div>
<div>{{class.teacher.rating}}</div>
</div>
现在您可以看到的模型有一个具有name属性和teacher属性的类对象。我想要做的是避免在此代码中重复,以便我的绑定看起来更像这样。
<div>{{class.name}}</div>
<div some-directive-here="class.teacher">
<div>{{name}}</div>
<div>{{age}}</div>
<div>{{rating}}</div>
</div>
angular是否支持指令,我可以为dom元素创建一个新的作用域,如上所示?我不想使用ng-controller,因为它创建了一个新的范围,并使我与原始模型数据断开连接。
答案 0 :(得分:1)
这是一个掠夺者:http://plnkr.co/edit/MqesLIUA1kq1S7BLal3N?p=preview
一个简单的指令,它创建一个新的范围,并使用它的父范围的计算表达式对其进行扩展。
app.directive('newScope', function($parse){
return {
scope:true,
compile: function (tElm,tAttrs){
var fn = $parse(tAttrs.newScope);
return function(scope, elm, attrs){
var property = fn(scope.$parent);
property = angular.isObject(property) ? property : {};
angular.extend(scope, property);
}
}
}
})
答案 1 :(得分:0)
解决方案的一个补充是考虑异步解决方案。我已经采用了plnkr示例并更新了编译函数,并在2秒后设置了class-property。
http://plnkr.co/edit/X8y3ArvTD3WDZIIB3qFk?p=preview
app.directive('newScope', function($parse){
return {
scope:true,
compile: function (tElm,tAttrs){
var init = false;
var attr = tAttrs.newScope;
var fn = $parse(attr);
var linkFunction = function (scope, elm, attrs) {
if (!init) {
scope.$watch(attr, function (newValue, oldValue) {
linkFunction(scope, elm, attrs);
});
}
var property = fn(scope.$parent);
property = angular.isObject(property) ? property : {};
angular.extend(scope, property);
init = true;
};
return linkFunction;
}
}
})