在angularjs中反转数组

时间:2015-05-20 12:27:47

标签: javascript angularjs

我是基础开发人员,只是想在发布表单后撤消我的数组列表,这是我的代码: -

app.js

    var app = angular.module('myApp');

app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {

$scope.form = {};
$scope.post = [];
$scope.submitForm = function () {
    $scope.post.text = $scope.form.text;
        if ($scope.post.text != '') {
            $scope.post.push($scope.post.text);           
            $scope.post.text = '';

        }

        $scope.remItem = function ($index) {

         $scope.post.splice($index , -1);
        }


       }
 }]);

我的HTML代码是: -

      <!DOCTYPE html>
     <html ng-app="myApp">

     <head>
     <link rel="stylesheet" href="style.css">
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
     <script src="script.js"></script>
     <script>
      myApp = angular.module('myApp', []);

     </script>
     </head>

     <body>
     <div ng-controller="WorkingCtrl" id="divmsg">
     <form name="myForm" ng-controller="WorkingCtrl" novalidate>
     <textarea cols="75" rows="3" placeholder="Share Your Knowledge !" ng-model="form.text"></textarea>
            <div id="row">
            <ul id="msgHolder" data-bind="foreach: posts">
                <li ng-repeat="userpost in post">
                      <p>
                        <a>
                         <b>User_name</b>
                        </a>
                      <div>
                      <span class="wordwrap">
                        {{ userpost }}
                      </span>
                      </div>
                   </p>
                </li>
            </ul>
        </div>
         <input type="button" align="right" style="margin-top: 0px; margin-bottom: 0px; margin-left: 78px; padding-top: 0px;" id="submit" ng-click="submitForm()" class="shoutButton" value="Post">
        </form>
            </div>
           </body>
        </html>

现在,无论用户从文本框中提交了什么内容,这都成功地为我提供了帖子,但它会转到数组的最后一个。

我想在第一个位置实现。怎么实现呢?这样任何用户的帖子都会被首先看到&amp;不是在最后。提前致谢 。 如果需要,以下是一个Plunker: - http://plnkr.co/edit/pVnSgVE8pfaHK1PxgatM?p=preview

1 个答案:

答案 0 :(得分:1)

使用unshift代替push

$scope.post.unshift($scope.post.text); 

工作示例:http://plnkr.co/edit/w1E3pcoWIBzHRRkib0jt?p=preview