输入上的角度ng模型不在ng-repeat内结合

时间:2015-05-01 18:40:44

标签: angularjs angularjs-ng-repeat angular-ngmodel

我正在尝试在提交时发布输入条目{{post.title}},但只发布{{post.upvotes}}。任何人都可以在我的代码中看到我可能没有看到的内容吗?

我提交的结果是   - upvotes:0

当我将{{post.title}}更改为{{title}}时,它发布得很好,但我无法弄清楚为什么它不会绑定到ng-model =“post”。

---
name: home
url: /
---
<br>
<div class="grid-container">
    <div class="grid-block">
      <div class="grid-block">
        <div id="chatBlock" class="small-12 medium-8 grid-content medium-order-1">
            <div ng-repeat="post in posts | orderBy: '-upvotes'">
              {{post.title}} - upvotes: {{post.upvotes}}
            </div>
            <br>
            <form ng-submit="addPost()">
              <input type="text" ng-model="title"></input>
              <button type="submit">Post</button>
            </form>
        </div>
        <div id="contacts" class="small-12 medium-4 grid-content medium-order-2">
            <div>{{test}}</div>
        </div>
     </div>
   </div>
</div>

app.js

(function() {
  'use strict';

  angular.module('chatter', [
    'ui.router',
    'ngAnimate',

    //foundation
    'foundation',
    'foundation.dynamicRouting',
    'foundation.dynamicRouting.animations'
  ])
    .config(config)
    .run(run)
    .controller('MainCtrl', [
      '$scope', 
      function($scope){
        $scope.test = 'Contacts';
        $scope.posts = [
        {title: 'test post', upvotes: 5}
        ];
        $scope.addPost = function(){   
          $scope.posts.push({title: $scope.title, upvotes: 0});
          $scope.title = '';
        };
}]);

  config.$inject = ['$urlRouterProvider', '$locationProvider'];

  function config($urlProvider, $locationProvider) {
    $urlProvider.otherwise('/');

    $locationProvider.html5Mode({
      enabled:false,
      requireBase: false
    });

    $locationProvider.hashPrefix('!');
  }

  function run() {
    FastClick.attach(document.body);
  }

})();

1 个答案:

答案 0 :(得分:1)

每当你传递post.title时,你强力绑定$scope.title,它永远不会给予价值。我相信你应该使用post.title&amp; post.upvotes&amp;在调用addPost时你应该传递post对象,以便更容易推送posts数组中的数据

        <form ng-submit="addPost(post)">
          <input type="text" ng-model="post.title"></input>
          <button type="submit">Post</button>
        </form>

<强>控制器

    $scope.addPost = function(post){   
      $scope.posts.push({title: post.title, upvotes: post.upvotes});
      //$scope.title = '';
    };