【问题标题】:Can't update $scope value in directive无法更新指令中的 $scope 值
【发布时间】:2015-12-11 21:32:17
【问题描述】:

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:

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

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

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

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多