2015-09-15 157 views
4

該指令火災:

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指令:

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

回答

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="[email protected]" 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>