gpt4 book ai didi

javascript - 在范围内单独使用 angularjs http json 结果

转载 作者:行者123 更新时间:2023-11-28 17:59:02 25 4
gpt4 key购买 nike

我使用 Angularjs $http 和 $scope 从 sql server 获取数据并在范围内成​​功显示它,没有任何问题。但是,当我尝试在同一范围内显示分离函数的 http json 结果时,什么也没发生。

所有我想知道的。如果我想在参数中获取 json 对象并在显示之前从中选择切片,我应该每次都发出 http 请求吗?或者我可以在独立函数中将作用域与 http 请求分开,如下所示。

<%--Angular--%>
<script src="../Scripts/angular.min.js"></script>
<script>

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

app.controller('myCtrl', function ($scope, $http) {
$http.get('../C_Angular.asmx/ShowSlider')
.then(function (response) {
jsonObj = response.data; // this part work well and retrieve data as expected by tracing C_Angular.asmx code
});
Select_From_Json = function (x, y) {
$scope.Categories = jsonObj.slice(x, y); // but this part don't work when I press Button1 to call Select_From_Json
};
});
</script>

当我按 Button1 调用 Select_From_Json 函数时,没有任何显示。

    <input id="Button1" type="button" value="button" onclick="Select_From_Json(2, 4)" />

<div data-ng-app="myApp" data-ng-controller="myCtrl">

<div data-ng-repeat="Cat in Categories">

<div style="background-image: url('{{Cat.Cat_Pic}}');">
<span>{{Cat.Cat_Name}}</span>
</div>

</div>

</div>

最佳答案

您的按钮超出了 Controller 范围。这就是 Select_From_Json 无法正确执行的原因。将按钮移动到定义 Controller 的 div 内。

<div data-ng-app="myApp" data-ng-controller="myCtrl">
<input id="Button1" type="button" value="button" onclick="Select_From_Json(2, 4)" />

<div data-ng-repeat="Cat in Categories">

<div style="background-image: url('{{Cat.Cat_Pic}}');">
<span>{{Cat.Cat_Name}}</span>
</div>

</div>

</div>

您还应该使用 ng-click 从 Controller 执行函数,如下所示:

    <div data-ng-app="myApp" data-ng-controller="myCtrl">
<input id="Button1" type="button" value="button" ng-click="select_From_Json(2, 4)" />

<div data-ng-repeat="Cat in Categories">

<div style="background-image: url('{{Cat.Cat_Pic}}');">
<span>{{Cat.Cat_Name}}</span>
</div>

</div>

</div>

在 Controller 本身中:

$scope.select_From_Json = function(x, y){
$scope.Categories = jsonObj.slice(x, y);
}

关于javascript - 在范围内单独使用 angularjs http json 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43917833/

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