双向绑定不会;似乎不起作用.列表不会自动更新

two way binding doesn't seem to work. List is not automatically updating

本文关键字:列表 更新 不起作用 绑定      更新时间:2023-09-26

我在更新列表时遇到问题。起初,我通过从$http.get请求中获取信息来填充列表。稍后,我在文本框中输入一些内容,并尝试使用$http.post请求的响应来更新列表。

我确实得到了回应,我有数据。当我覆盖$scope中的变量时,列表不会更新。

我的代码如下:

'use strict';
angular.module('myApp.friends', ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/friends', {
            templateUrl: 'friends/friends.html',
            controller: 'FriendsCtrl'
        });
    }])
    .controller('FriendsCtrl', function ($scope, $http, $timeout, UserService) {
        $scope.items = [];
        $scope.formSearchData = {};
        UserService.getAll().then(function(data) {
            var remoteItems = data;
            for (var i = 0; i < remoteItems.length; i++) {
                var object = {};
                object.name = remoteItems[i].name;
                object.id = remoteItems[i]._id;
                $scope.items.push(object);
            }
        });
        $scope.itemClick = function(value) {
            console.dir(value);
        };
        $scope.submitForm = function() {
            //debugger;
            $scope.items[0].name = "John D";
            UserService.getSearchResult($scope.formSearchData).then(function(data) {
                getSearchResult(data);
            });
        };
        function getSearchResult(data) {
            var remoteItems = data.records;
            $scope.items = [];
            for (var i = 0; i < remoteItems.length; i++) {
                var object = {};
                object.name = remoteItems[i].name;
                object.id = remoteItems[i].id;
                $scope.items.push(object);
            }
        }
    })
    .controller('navigationcontroller', function ($scope, $location) {
        $scope.isActive = function(viewLocation) {
            return viewLocation = $location.path();
        }
    });
<div class="panel panel-title">
    <div class="panel-body">
        <div class="friend-search" ng-controller="FriendsCtrl">
            <form ng-submit="submitForm()">
                <input type="search" name="search" placeholder="Zoek vrienden" class="form-control" ng-model="formSearchData.search">
            </form>
        </div>
    </div>
</div>
<div class="panel panel-title">
    <div class="panel-default">
        <div class="scrollable-content" ui-scroll-bottom='bottomReached()' ng-controller="FriendsCtrl">
            <div class="list-group">
                <a ng-repeat="item in items" ng-model="items" class="list-group-item" ng-click="itemClick(item)">
                    {{ item.name }}
                </a>
            </div>
        </div>
    </div>
</div>

UserService是一个具有两个功能的工厂,一个用于GET请求,另一个用于POST请求。它看起来像这样:

angular.module('myApp').factory('UserService', function($http) {
    return {
        getAll: function() {
            return $http.get('http://localhost:3030/user/all').then(function(response) {
                return response.data;
            });
        },
        getSearchResult: function(query) {
            return $http.post('http://localhost:3030/user/search', query, { 'Content-Type': 'application/json' }).then(function(response) {
                return response.data;
            });
        }
    };
});

我读到一些关于$scope超出范围的文章,并试图通过使用$scope.apply()或$scope来解决它$消化,但我尝试时会出错。我还尝试在html中添加跟踪,但似乎也不起作用。

正如你所看到的,我也尝试过对列表进行硬编码更新,但似乎也不起作用。

我是Angular的新手,这让我忙了好几天。我希望有人能帮助我。欢迎对我的代码提出任何建议;)。谢谢

这里有一个只使用一个控制器的代码库。我对它做了一些修改,因为我没有API端点,但返回的对象是一个承诺,因此数据可以正确显示。

http://plnkr.co/edit/iEWBm6QE2pmFqbsU6EiB?p=preview

代码不能按预期工作的原因是您在HTML中声明了两次控制器。

从角度文档:

当控制器通过ng-Controller指令连接到DOM时,Angular将使用指定的控制器的构造函数实例化一个新的控制器对象。将创建一个新子作用域,并将其作为控制器构造函数的可注入参数$scope

含义:

当您声明另一个ng控制器时,它有自己的子作用域,它不与任何其他控制器共享作用域。并且您的项仅在一个作用域上声明。

相关代码:

var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', 'UserService', function($scope, UserService){
  $scope.items = [];
  $scope.formSearchData = {};
  UserService.getAll().then(function(data) {
      $scope.saved = data;
      for (var i = 0; i < $scope.saved.length; i++) {
          var object = {};
          object.name = $scope.saved[i].name;
          object.id = $scope.saved[i]._id;
          $scope.items.push(object);
      }
  });
  $scope.itemClick = function(value) {
      console.dir(value);
  };
  $scope.submitForm = function() {
      UserService.getSearchResult($scope.formSearchData).then(function(data) {
          console.log( data );
          if( data ){
            $scope.items = data;
          } else {
            $scope.data = $scope.saved;
          }
      });
  };

}]); 
app.factory('UserService', function($http, $q) {
    return {
        getAll: function() {
          return $q(function(resolve, reject) {
            resolve(
              [{
                name: 'test'
              }, {
                name: 'test2'
              }]
            );
          });
            /*return $http.get('http://localhost:3030/user/all').then(function(response) {
                return response.data;
            });*/
        },
        getSearchResult: function(query) {
          return $q(function(resolve, reject) {
            resolve( [{
              name: 'test'
            }]);
          });
          /*  return $http.post('http://localhost:3030/user/search', query, { 'Content-Type': 'application/json' }).then(function(response) {
                return response.data;
            });*/
        } 
    }; 
});