无法在指令中更新$ scope值

时间:2015-09-15 14:54:43

标签: javascript html angularjs

ng-repeat使用scope.$last完成时会触发此指令:

simpleSearchApp.directive('afterResults', function($document) {
 return function(scope, element, attrs) {
   if (scope.$last){
    scope.windowHeight = $document[0].body.clientHeight;
   }
 };
});

我尝试使用新值更新$scope.windowHeight但我无法在指令中访问$scope

我的ng-repeat HTML with directive:

 <div ng-show="items" class="ng-cloak" ng-repeat="item in items" after-results>
     {{item}}
 </div>

1 个答案:

答案 0 :(得分:0)

老实说我也不明白为什么不更新。但是在控制器中更新变量的替代方法是定义一个更新变量的函数,并在指令中调用控制器中的该函数。请看一下它可能对您有帮助的以下示例。

angular.module('app',[]).controller('MyController',['$scope',function($scope){
  $scope.windowHeight = 0;
  
  $scope.updateWindowHeight = function(height){
    $scope.windowHeight = height;
  }
  
}])
.directive('afterResults', function($document) {
 return function(scope, element, attrs) {
   if (scope.$last){
      scope.windowHeight = $document[0].body.clientHeight;
      scope.updateWindowHeight( scope.windowHeight);//calling function in controller
   }
 };
});
 
 
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script data-require="angular.js@1.4.1" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="MyController">
  <div class="ng-cloak" ng-repeat="item in [1,2,3,4,5]" after-results="updateWindowHeight()">
    {{item}}
  </div>
  <hr/>{{ "$scope.windowHeight ="+windowHeight}}
</body>

</html>