gpt4 book ai didi

html - AngularJs 将 http 响应对象分配给来自 html 的范围

转载 作者:可可西里 更新时间:2023-11-01 17:01:15 25 4
gpt4 key购买 nike

这是我第一次使用 AngularJs,我非常感谢对此的一些帮助。

我有一个 json 文件,我正在从中检索一些显示在我的 html 模板上的内容。到目前为止一切顺利。

我需要将 http 响应数据分配给 html 中的范围。

这是我的应用

var myApp = angular.module('myApp', ['ngMessages']);

myApp.controller('mainController', ['$scope', '$filter', '$http', '$log', function($scope, $filter, $http, $log) {

$scope.url = "myurl";

$http.get($scope.url)
.success(function(result) {

$scope.page = result;

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

$log.info(data);

});

$scope.$watch('productId', function () {
$log.info($scope.productId);
});

}]);

这是html

<div class="page" ng-controller="mainController">

<div id="content" class="chapter">

<h1>The Icons Update</h1>

<div ng-init="productId = page[0].acf.spotlight_on"></div>

<p>{{ page[0].acf.spotlight_on_title }}</p>
<p>{{ page[0].acf.spotlight_on_paragraph }}</p>
<img src="{{ page[0].acf.stylist_picture }}" />

</div>
</div>

我需要将 page[0].acf.spotlight_on 的值分配给 productId,但需要从 html 中进行。我只是得到一个未定义的值。

我应该在 div 上使用 ng-init 还是应该使用不同的方法?有没有其他方法可以实现我的需要?

最佳答案

我的理解是ng-init在解决 promise 后不能用于设置范围值,这是从 $http.get 设置值时发生的情况.请参阅 ngInit 的 Angular 文档 https://docs.angularjs.org/api/ng/directive/ngInit

在您的问题中,您说您需要设置 productId 的值在 html 中,但是在 promise 返回的情况下这似乎是不可能的。

替代方案非常简单,只需使用以下命令即可在 Controller 中完成:

var myApp = angular.module('myApp', ['ngMessages']);

myApp.controller('mainController',
['$scope', '$filter', '$http', '$log',
function($scope, $filter, $http, $log) {

$scope.page = {};
$scope.productId = '';

$scope.url = "myurl";
$http.get($scope.url)
.success(function(result) {
$scope.page = result;
// set the value of productId from the result
$scope.productId = result[0].acf.spotlight_on;
})
.error(function(data, status) {
$log.info(data);
});
}]);

关于html - AngularJs 将 http 响应对象分配给来自 html 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33711275/

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