如何在指令中绑定 DOM 属性

How to bind DOM property in directive

给出这个例子:

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 元素?我希望 angular 属性在 DOM 元素更改时更改。

在您的指令中使用 window "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();
        });
      }
    }
  })

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