0

给定这个例子:

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 元素更改时更改角度属性。

4

1 回答 1

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您已经拥有该指令创建的该元素的范围。

于 2016-01-04T13:22:58.200 回答