gpt4 book ai didi

angularjs - angular.js 在回调中触发 ng-show

转载 作者:行者123 更新时间:2023-12-03 21:49:50 25 4
gpt4 key购买 nike

我试图通过在 setTimeout 函数中编辑范围来触发 ng-show。 setTimeout 是数据库查询回调的占位符。

索引.html:


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

<script src="script.js"></script>


<div ng-controller="c1">

<div ng-show="{{show}}" >

test it

</div>

</div>



脚本.js:
var amTestNgShow = angular.module('amTestNgShow',[]);

amTestNgShow.controller('c1', ['$scope', function($scope) {

// this works: $scope.show = true;

setTimeout(function(){

$scope.show = true; // works not

// does not help: $scope.$apply();

}, 1000)

}]);

这在 setTimeout 内如何实现?谢谢!

http://plnkr.co/edit/RPS2vZAlVfhliQKteSSK

更新:如上所述, setTimeout 不是问题,它仅用于生成可重现的 stackoverflow 问题。在我的项目中,我构建了一个服务:
amProject1.service('asBasic', ['$http', '$q', function($http, $q){

var asBasic = {};

asBasic.docName = '';

var doc = {};

asBasic.get = function(id){

var deferred = $q.defer();

$http({method:'GET', url: '/' + this.docName + '/' + id})
.success(function(data, status, headers, config){

if(data === undefined){

deferred.reject("The requested " + asBasic.docName + " was not found.")

}

doc = data;
deferred.resolve(doc);

})
.error(function(data, status, headers, config){

deferred.reject(status);

})

return deferred.promise;

}


return asBasic;

}]);

像使用它一样
amProject1.controller('acDoc1', ['$scope', '$routeParams', 'asBasic', function($scope, $routeParams, asBasic){

asBasic.docName = 'doc1';

// this works: $scope.show = true;

asBasic.get($routeParams._id)
.then(function(data){

$scope.doc1 = data;

$scope.show = true; // works not

// does not help: $scope.$apply();

// ...

}
// ...

最佳答案

这是因为 setTimeout 在 $scope 之外。过程。注入(inject)使用$timeout反而。

http://docs.angularjs.org/api/ng/service/$timeout

例如:

amTestNgShow.controller('c1', ['$scope', '$timeout', function($scope, $timeout) {
$timeout(function(){
$scope.show = true;
}, 1000);
}]);

如果您确实想改用 $scope.apply ,我认为您只是使用错误。您不调用 $scope.apply()在您的范围编辑之后,您将它们放在 apply 函数中:
$scope.apply(function(){
$scope.show = true;
});

关于angularjs - angular.js 在回调中触发 ng-show,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23104410/

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