【问题标题】:Not able to access scope variable from HTML无法从 HTML 访问范围变量
【发布时间】:2016-04-12 06:51:14
【问题描述】:

我正在尝试检索远程服务器上的文件列表并将它们显示在网页上。 范围变量fileListOnCTP 保存从网页访问的文件列表。但网页不显示文件列表。然而 ng-inspector 显示变量持有正确的值。谁能告诉我哪里出错了?

$scope.listOfFilesOnCTP = "";
	$scope.fileListOnCTP = "";
	$scope.GetListOfFilesonCTP = function(path){ 
	$scope.listOfFilesOnCTP = RdaService.getListOfFilesonCTP(encodeURIComponent(path)).then(function(response){
			var newData = response.data;
			console.log(newData);
			return newData;
		 });
	console.log($scope.listOfFilesOnCTP);  // --> Displaying the file list correctly
		//path = path.replace(/\//g, '_');
	$scope.fileListOnCTP = $scope.listOfFilesOnCTP;  
	};
	<div class="col-md-3" id="CTP Jobs">
		<h3>JOBS</h3>
		<table class="table table-striped">
			<div ng-model="fileListOnCTP" ng-init="GetListOfFilesonCTP('/home/topas/rda_app/JOBS')">
				<span><tr>{{fileListOnCTP}}  <!-- Variable not getting resolved although it shows correct value in controller -->
					</tr></span>
			</div>
		</table>
	</div>

【问题讨论】:

  • 你不能简单地在 DIV 上做一个ngModel,只能在输入/文本区域上(除非你使用需要 ngModel 的指令)
  • 如果返回值是一个数组,你可能需要一个 ng-repeat。 fileListOnCTP 的类型是什么?
  • 感谢您的反馈.. 但是如果不使用 ng-model 我也没有运气..
  • @BobS 它是一个字符串
  • 根据您提供的代码$scope.listOfFilesOnCTP$scope.fileListOnCTP 都是承诺,因此它们不会具有您正在寻找的价值,您是否尝试在您的.then 中设置$scope.fileListOnCTP? (例如:$scope.fileListOnCTP = newData 或类似的东西)

标签: javascript html angularjs angularjs-scope


【解决方案1】:

由于您的RdaService.getListOfFilesonCTP 返回一个承诺,您需要更新then 内的$scope 变量,因为您可以在此处获得承诺的解析值。如果您尝试在别处设置您的 $scope 变量,则无法保证该服务会返回一个值,这就是您之前的代码不起作用的原因。

供参考:https://docs.angularjs.org/api/ng/service/$q#the-promise-api

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2013-06-12
    相关资源
    最近更新 更多