【问题标题】:How to bind DOM property in directive如何在指令中绑定 DOM 属性
【发布时间】:2016-04-04 23:15:12
【问题描述】:

举个例子:

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 指令的高度和宽度绑定到DOM 元素?我希望在 DOM 元素更改时更改角度属性。

【问题讨论】:

  • 那么您真正想要的是父级上的自定义指令,当父级调整大小时更新范围变量?在这种情况下,向我们展示无效的指令并询问我们如何修复它。
  • minimal reproducible example更新了问题。

标签: css angularjs data-binding ng-style


【解决方案1】:

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

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();
        });
      }
    }
  })

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    相关资源
    最近更新 更多