Unable to update $ scope value in directive

This directive fires when it ng-repeatfinishes using scope.$last:

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

I am trying to update with a $scope.windowHeightnew value, but I cannot access the $scopeinside of the directive.

My ng-repeatHTML with the directive:

 <div ng-show="items" class="ng-cloak" ng-repeat="item in items" after-results>
     {{item}}
 </div>
+4
source share
1 answer

Honestly, I also do not understand why it is not being updated. But an alternative approach to updating a variable in the controller is to define a function that updates the variable and calls this function in the controller from the directive. Please take a look at the following example that may help you.

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>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1607495/


All Articles