gpt4 book ai didi

css - 如何在指令中绑定(bind) DOM 属性

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:50 24 4
gpt4 key购买 nike

给出这个例子:

var SomeApp = angular.module('SomeApp', [])
.controller('SomeController', function($scope){
$scope.items = [0,1,2,3]
})
.directive('gridResize', function(){
return {
scope: true,
link: function(scope, elem) {
scope.gridResize = {
width: $(elem).width(),
height: $(elem).height()
};
}
}
})
.parent {
width: 80%;
position: relative;
left: 50%;
transform: translateX(-50%);
border: 1px solid red;
}
.parent > * {
background-color: rgba(0,0,0,.14);
margin-bottom: 1px;
padding: 20px;
box-sizing: border-box;
}
.parent > *:last-child {
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="SomeApp">
<div class="parent" ng-controller="SomeController" grid-resize>
<div ng-style="{'min-height':($parent.gridResize.width/8) + 'px'}"
ng-repeat="item in items"
>
height: {{$parent.gridResize.height}} | width: {{$parent.gridResize.width}}
</div>
</div>
</div>

谁能告诉我如何将 grid-resize 指令的高度和宽度绑定(bind)到 DOM 元素?我希望 Angular 属性在 DOM 元素更改时更改。

最佳答案

在您的指令中使用窗口“调整大小”事件来更新范围的大小:

var SomeApp = angular.module('SomeApp', [])
.controller('SomeController', function($scope){
$scope.items = [0,1,2,3]
})
.directive('gridResize', function(){
return {
scope: false,
link: function(scope, elem) {
scope.gridResize = {
width: $(elem).width(),
height: $(elem).height()
};
angular.element(window).on('resize', function(e) {
scope.gridResize = {
width: $(elem).width(),
height: $(elem).height()
};
scope.$apply();
});
}
}
})

另请注意,我将指令的范围更改为“false”。您已经拥有由 ng-controller 指令创建的该元素的范围。

关于css - 如何在指令中绑定(bind) DOM 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34538687/

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