gpt4 book ai didi

javascript - 无法更新指令中的 $scope 值

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:44 24 4
gpt4 key购买 nike

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>

最佳答案

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

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>

关于javascript - 无法更新指令中的 $scope 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32589241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com