在角度为js的ng-grid中插入行

时间:2017-03-25 09:39:39

标签: javascript angularjs ng-grid

我是角度js的新手。 我试图在点击按钮时在ng-grid中插入行。 为此,我编写了一个更新json对象的函数addNewItems()。 但网格未显示更新的对象。 这是我的代码:

<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8">
<title>Getting Started With ngGrid Example</title>
<link rel="stylesheet" type="text/css" href="script/ng-grid.css" />
<link rel="stylesheet" type="text/css" href="script/indexStyle.css" />
<script type="text/javascript" src="script/jquery-2.1.4.js"></script>
<script type="text/javascript" src="script/angular.min.js"></script>
<script type="text/javascript" src="script/ng-grid-1.3.2.js"></script>
<script>
      var myData = [{name: "Moroni", age: 50},
                    {name: "Tiancum", age: 43},
                    {name: "Jacob", age: 27},
                    {name: "Nephi", age: 29},
                    {name: "Enos", age: 34}];
      var app = angular.module('myApp', ['ngGrid']);
      app.controller('MainCtrl', function($scope) {
          $scope.gridOptions = { data: myData };

          $scope.addNewItem=function()
          {
           myData.push( { name: 'Test add ', age:29});

           $scope.gridOptions = { data: myData };

          };          
          console.log(myData);
      });

      </script>
</head>
<div ng-controller="MainCtrl">
    <div class="gridStyle" ng-grid="gridOptions">
        <button ng-click="addNewItem()">ADD item</button>
    </div>
    </body>
</html>

4 个答案:

答案 0 :(得分:0)

请检查一下。 只需从js:

中删除此代码即可
$scope.gridOptions = { data: myData };

答案 1 :(得分:0)

你可以试试这个。

app.controller('MainCtrl', function($scope) {
     $scope.data = myData;
     $scope.gridOptions = { data: 'data' };
     ...

答案 2 :(得分:0)

试试这个

app.controller('MainCtrl', function($scope) {
    $scope.gridOptions = { data: myData };

    $scope.addNewItem = function() {
        $scope.gridOptions.data.push({ name: 'Test add ', age: 29 });
    };
    console.log($scope.gridOptions.data);
});

答案 3 :(得分:0)

嘿谢谢@Gurkan Yesilyurt,@ anan程序员,@ Gaurav,@ kinjal jethva

这样做了,它开始工作了:

var myData = [{name: "Moroni", age: 50},
                    {name: "Tiancum", age: 43},
                    {name: "Jacob", age: 27},
                    {name: "Nephi", age: 29},
                    {name: "Enos", age: 34}];
      var app = angular.module('myApp', ['ngGrid']);
      app.controller('MainCtrl', function($scope) {
             $scope.data = myData;
             $scope.gridOptions = { data: 'data' };

            $scope.addNewItem = function() {
                $scope.data.push({ name: 'Test add ', age: 29 });
            };
            console.log($scope.gridOptions.data);
        });