ng-repeat / ng-bind不会显示我的数据

时间:2015-01-23 11:33:11

标签: javascript angularjs angularjs-scope ng-repeat ng-bind

我得到的问题是我的ng-repeat / ng-bind不会显示$ scope.articles中的数据。而在控制台中我得到的数据我期待。 我现在制作了一个代码snippit,以便更容易发现问题。



var App = angular.module('App', []);
App.controller('WebCtrl', function($scope, $http) {

  $scope.start = [{
    "id": 1,
    "text": "test1"
  }, {
    "id": 2,
    "text": "test2"
  }, {
    "id": 3,
    "text": "test3"
  }, {
    "id": 4,
    "text": "test4"
  }];
  $scope.articles = $scope.start;

  $http.get('/')
    .then(function() {
      $scope.menu = function(id) {
        $scope.articles = $scope.start[id];
        console.log($scope.articles);
      }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html ng-app="App">

<head>
  <meta charset="utf-8">
  <title>Todos $http</title>
  <script src="app.js"></script>
</head>

<body ng-controller="WebCtrl">
  <ul>
    <li style="list-style: none">
      <button ng-click="menu(0)">1</button>
      <button ng-click="menu(1)">2</button>
      <button ng-click="menu(2)">3</button>
      <button ng-click="menu(3)">4</button>
    </li>
  </ul>

  <ul>
    <li style="list-style: none" ng-repeat="article in articles">
      {{article.text}}
    </li>
  </ul>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的代码以指向数组的文章对象开头。在内部菜单中,它被一个对象取代。 ng-repeat迭代其键。

我猜主要的变化是:

$scope.articles = $scope.start.slice(id, id + 1);

&#13;
&#13;
var App = angular.module('App', []);
App.controller('WebCtrl', function($scope, $http) {

  $scope.start = [{
    "id": 1,
    "text": "test1"
  }, {
    "id": 2,
    "text": "test2"
  }, {
    "id": 3,
    "text": "test3"
  }, {
    "id": 4,
    "text": "test4"
  }];
  $scope.articles = $scope.start;

      $scope.menu = function(id) {
        $scope.articles = $scope.start.slice(id, id + 1);
        console.log($scope.articles);
      }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html ng-app="App">

<head>
  <meta charset="utf-8">
  <title>Todos $http</title>
  <script src="app.js"></script>
</head>

<body ng-controller="WebCtrl">
  <ul>
    <li style="list-style: none">
      <button ng-click="menu(0)">1</button>
      <button ng-click="menu(1)">2</button>
      <button ng-click="menu(2)">3</button>
      <button ng-click="menu(3)">4</button>
    </li>
  </ul>

  <ul>
    <li style="list-style: none" ng-repeat="article in articles">
      {{article.text}}
    </li>
  </ul>
</body>

</html>
&#13;
&#13;
&#13;