gpt4 book ai didi

angularjs - 如何绑定(bind)指令范围的深层子属性?

转载 作者:行者123 更新时间:2023-12-02 23:18:52 25 4
gpt4 key购买 nike

亲爱的 friend 们,

我们可以将指令的范围属性绑定(bind)到 DOM 属性的值。

这有效:

module.directive 'MyDirective', ->
scope:
directiveVar: '='

...

<div class='MyDirective' directive-var='parentVar'></div>

在上面的示例中,我们将指令的 directiveVar 属性绑定(bind)到父作用域的 parentVar 属性。

这是双向绑定(bind),因此如果 directiveVar 发生更改,parentVar 会自动更新,反之亦然。

我的问题是:

有没有办法可以绑定(bind)指令范围的深层子属性?像 scope.lv1.directiveVarscope.lv1.lv2.lv3.directiveVar 而不是 scope.directiveVar

Docs I read

我想要实现的目标

我在指令范围内有一个名为 lv1 的对象。我想将其属性directiveVar绑定(bind)到父属性。

这不起作用:

scope:
lv1:
directiveVar: '='

这不起作用:

scope:
"lv1.directiveVar": '=myVar'
<小时/>

演示

这就是有效的:http://plnkr.co/edit/OClnZ2Cl3BXr60PC2qVP?p=preview

这就是我想要实现的目标:http://plnkr.co/edit/tQEHeKOzGjGyplCwUtU2?p=preview

最佳答案

我希望这段代码能有所帮助。您可以传入一个对象并观察其属性,也可以将内容嵌套在父/子指令中。无论哪种方式添加“=”都将在整个对象上启用双向绑定(bind)。

Controller :

$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我相信演讲者触及了一些面向对象的模式。

编辑2:

您可以使用服务 like this plunker

关于angularjs - 如何绑定(bind)指令范围的深层子属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com