Angular不更新范围更改模板

时间:2016-02-27 07:14:00

标签: javascript angularjs

当输入框中的日期发生变化时,我正在尝试更新我的模板。

我的输入框html是:

<div class="col-md-4 pull-right">
    <input type="text" id="id_date" class="form-control" ng-model="date" ng-change="sendPost()" value="{{ date }}"/>
</div>

我的表格模板是:

<tr>
    <td style="font-weight: bold">term</td>
    <td ng-repeat="block in blocks">{{ data[block]['term'] }}</td>
    <td>{{ total['term'] }}</td>
</tr>

最后我的控制器代码是:

$scope.blocks = ['A', 'B', 'C'];
$scope.data = {'A': {'term': 0, 'term2': 7}, 'B': {'term': 2, 'term2': 3}, 'C': {'term': 5, 'term2': 14}};
$scope.total = {'term': 50, 'term2': 70};
$scope.date = "2016-01-01";

$scope.sendPost = function() {
    //console.log("working");
    var post_data = {"date": $scope.date};

    $http.post("/web_api", post_data).success(function (post_data, status) {
        $scope.data = post_data.data;
        $scope.total = post_data.total;
        console.log($scope.data);
        console.log($scope.total);
    }).error(function(response) {
        //console.log(response);
          $scope.error = 'ERROR';
      });
};

控制台日志正在发布请求中返回所需的对象。

4 个答案:

答案 0 :(得分:0)

每当你在 angularjs 之外进行某种形式的操作时,你需要让angular知道更新自己。

尝试添加$ scope。$ apply();之后

$scope.data = post_data.data;
$scope.total = post_data.total;

在您的帖子请求中,它可能会有效。

$scope.$apply()

上查看更多内容

答案 1 :(得分:0)

尝试将范围分配块包装在$ timeout中,这会将操作发送到que的末尾。像这样:

$http.post("/web_api", post_data).success(function (post_data, status) { $timeout(function(){ $scope.data = post_data.data; $scope.total = post_data.total; console.log($scope.data); console.log($scope.total); }); }).error(function(response) { //console.log(response); $scope.error = 'ERROR'; });

答案 2 :(得分:0)

.success.error已弃用,但仍然有效。但是,它们会提供原始数据响应。

您正在尝试使用response.data,但没有这样的事情。

// This is the old way. It still works, but you get a raw data response.
$http.post("/web_api", post_data).success(function (post_data, status) {
    $scope.data = post_data;  // <-- Fixed!
    $scope.total = post_data.total; // <-- There is no such thing.
    console.log($scope.data);
    console.log($scope.total);
}).error(function(response) {
    //console.log(response);
      $scope.error = 'ERROR';
  });

更好的是,使用新的方式:

$http.post(...).then( onSuccess, onError );

onSuccess中,您可以使用$ scope.data = post_data.data;

$http.post(...).then(function(post_data){
    $scope.data = post_data.data;
});

除此之外,您的代码工作正常。我彻底地试了一下。

https://docs.angularjs.org/api/ng/service/$http#deprecation-notice

答案 3 :(得分:0)

您的 $ http承诺不同。查看https://docs.angularjs.org/api/ng/service/$http

试试这个:

$http
.post('/web_api', post_data)
.then(function(response) {
    // success

    $scope.data = post_data.data;
    $scope.total = post_data.total;
    console.log($scope.data);
    console.log($scope.total);
}, function(response) {
    // error

    //console.log(response);
    $scope.error = 'ERROR';
})
.finally(function() {
    // finally.. like for disable loader ?! 
});