绑定不更新$ scope。$ apply在$ http内

时间:2016-01-12 14:36:35

标签: .net angularjs

第一次使用Angular,我试图简单地从http请求更新一些绑定。我的回复正确,但我似乎无法让更改生效。理想情况下,我希望响应以类似于已注释掉的代码的方式更新。如果我的设置有误,请告诉我,因为我是Angular的新手。

JS

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

app.controller("index", function ($scope, $http) {
    $scope.sendCall = function () {
        $http({
            url: "AngularJS.aspx/GetObject",
            method: "POST",
            data: {}
        })
        .then(function (response) {
            $scope.$apply(function () {
                //$scope = response.data.d;
                $scope.Name = "me";
            });
        },
        function (response) {

        });
    }
});

HTML

    <div ng-app="nameApp" ng-controller="index">

        Name: <input type="text" ng-model="Name" />
        Favorite Color: <input type="text" ng-model="Color" />
        <br>
        Details: {{Name}}<br />
        <button ng-click="sendCall()">Run!</button>
    </div>

1 个答案:

答案 0 :(得分:2)

您不应该申请。如下所示:

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

app.controller("index", function ($scope, $http) {
    $scope.sendCall = function () {
        $http({
            url: "AngularJS.aspx/GetObject",
            method: "POST",
            data: {}
        })
        .then(function (response) {
             $scope.Name = response.data.d;
        },
        function (response) {
            //err
        });
    }
});

HTML:

<div>
    {{Name}}
</div>