无法在angularjs中调用$ http

时间:2019-03-23 11:11:15

标签: javascript angularjs asp.net-mvc

我想通过http调用服务以获取angularjs中的下拉列表。但是,该函数不会执行http服务方法。

im通过ajax调用绑定下拉列表,在绑定ajax调用之后,我想显示ajax调用中所选值的详细信息。

 <script type="text/javascript">
    var app = angular.module('myApp', [])
    app.controller('myCtrl', function ($scope, $http, $window) {
        $scope.DefaultLabel = "Loading.....";
        var post = $http({
            method: "POST",
            url: "/PIRDetails/AjaxMethod",
            dataType: 'json',
            data: {},
            headers: { "Content-Type": "application/json" }
        });
        post.success(function (data, status) {
            $scope.DefaultLabel = "Please Select PIR Device";
            $scope.Customers = data;
        });
        post.error(function (data, status) {
            $window.alert(data.Message);
        });

        $scope.getPIRData = function (id) {
            $http.get("/PIRDetails/GetPIRStatus/e203")
                .then(function (response) {
                    $scope.myWelcome = response.data;
                });
        };
    });

</script>
<div ng-app="myApp" ng-controller="myCtrl">
    <select class="form-control" onchange="getPIRData(this.value);">
        <option value="0" label="{{DefaultLabel}}"></option>
        <option ng-repeat="customer in Customers" value="{{customer.Value}}">{{customer.Text}}</option>
    </select>
</div>

2 个答案:

答案 0 :(得分:2)

尝试ng-change而不是onchange

<div ng-app="myApp" ng-controller="myCtrl">
    <select class="form-control" ng-change="getPIRData(this.value);">
        <option value="0" label="{{DefaultLabel}}"></option>
        <option ng-repeat="customer in Customers" value="{{customer.Value}}">{{customer.Text}}</option>
    </select>
</div>

一个demo code here

答案 1 :(得分:1)

正如@评论中提到的@sinkatonte,您使用angularjs的方式是完全不正确的。您无需在函数内定义angularjs应用程序和控制器。使用以下方法更正您的代码。

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
    $scope.getPIRData = function(id) {
        $http.get("/PIRDetails/GetPIRStatus/e203")
            .then(function (response) {
                $scope.myWelcome = response.data;
        });
   };
});


<div ng-app="myApp" ng-controller="myCtrl">
    <select class="form-control" ng-change="getPIRData(this.value);">
        <option value="0" label="{{DefaultLabel}}"></option>
        <option ng-repeat="customer in Customers" value="{{customer.Value}}">{{customer.Text}}</option>
    </select>
</div>

确保$ http中的response.data返回数据的格式正确,并且在ng-change =“ getPIRData(this.value)

中使用this.value的值