亲爱的朋友们,
我们可以将指令的scope属性绑定到DOM属性的值。
这有效:
module.directive 'MyDirective', ->
scope:
directiveVar: '='
...
<div class='MyDirective' directive-var='parentVar'></div>
在上面的示例中,我们将指令的directiveVar
属性绑定到父作用域的parentVar
属性。
这是双向绑定,因此如果更改directiveVar
parentVar
会自动更新,反之亦然。
我的问题是:
有没有办法可以绑定指令范围的深子属性?与scope.lv1.directiveVar
或scope.lv1.lv2.lv3.directiveVar
而不是scope.directiveVar
一样?
我想要实现的目标
我在指令范围内有一个名为lv1
的对象。我想将其属性directiveVar
绑定到父属性。
这不起作用:
scope:
lv1:
directiveVar: '='
这不起作用:
scope:
"lv1.directiveVar": '=myVar'
演示
这是有效的:http://plnkr.co/edit/OClnZ2Cl3BXr60PC2qVP?p=preview
这就是我想要实现的目标:http://plnkr.co/edit/tQEHeKOzGjGyplCwUtU2?p=preview
答案 0 :(得分:2)
我希望这段代码会有所帮助。您可以传入一个对象并查看其属性,也可以在父/子指令中嵌套。无论哪种方式添加“=”都将启用对整个对象的双向绑定。
<强>控制器:强>
$scope.directiveVar = {
level1: {
greeting: 'Hello'
}
};
$scope.otherVar = {
levelA: {
foo: 'bar'
}
};
的标记:强>
<div data-my-parent-directive data-other-var="otherVar">
<div data-my-directive data-directive-var="directiveVar"></div>
</div>
的指令:强>
angular.module('MyDirective', [])
.directive('myParentDirective', ['$window',
function ($window) {
return{
restrict: 'AE',
scope:{
otherVar: '='
},
controller: function($scope, $element) {
var othis = this;
this.element = $element;
this.otherVar = $scope.otherVar;
}
};
}
])
.directive('myDirective', ['$window',
function ($window) {
return {
restrict: 'AE',
require: '?myParentDirective',
scope: {
directiveVar: '='
},
link: function(scope, elm, attr, myParentDirectiveCtrl) {
console.log(myParentDirectiveCtrl.otherVar);
console.log(myDirectiveParentCtrl.otherVar.levelA);
scope.$watch('directiveVar.level1', function (newValue, oldValue){
console.log(newValue, oldValue);
});
}
};
}
])
<小时/> 修改强>
你可以这样做:
<div data-my-parent-directive data-other-var="otherVar">
<div data-my-directive data-directive-var="directiveVar.level1"></div>
</div>
在建模数据时很有用。例如:
var items = apiService.getItems();
var layers = [...],
$scope.map = {
points: items,
layers: layers,
highAltMap: 'Streets',
lowAltMap: 'Satellite'
};
如果您正在建模数据,请参阅此ng-conf video,我相信发言人已经触及了一些OO模式。
编辑2:
您可以使用服务like this plunker
答案 1 :(得分:0)
我知道问题的日期,但是......
Create json object in attribute
return {
scope: {
date: "=",
formChange: "=?",
ngDisabled: "=?",
deepInclude: "=?"
},
...
&#13;
<user-date-without-current-date date="cv.dateBirthday" deep-include="{cnt:cv.dateBirthday}" form-change="$parent.form_change"></user-date-without-current-date>
&#13;
有用吗?