繁体   English   中英

双向绑定似乎不起作用。 列表未自动更新

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

我在更新列表时遇到麻烦。 首先,我通过从$ 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。$ digest来解决,但尝试此操作时出现错误。 我也尝试在html中添加跟踪,但这似乎也不起作用。

如您所见,我还尝试对列表进行硬编码,这似乎也不起作用。

我是Angular的新手,现在让我忙了好几天。 我希望有一个人可以帮助我。 也欢迎对我的代码提出任何建议;)。 谢谢!

这是仅使用一个控制器即可完成的代码编写工作。 由于没有您的API端点,我对其做了一些修改,但是返回的对象是一个Promise,因此可以正确显示数据。

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

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

从角度文档:

“当通过ng-controller指令将Controller附加到DOM时,Angular将使用指定的Controller的构造函数实例化一个新的Controller对象。将创建一个新的子作用域并将其作为可注入的参数提供给Controller的构造函数作为$ scope。”

含义:

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

相关代码:

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;
            });*/
        } 
    }; 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM