无法从Angular.js中的控制器获取数据

时间:2016-04-03 11:18:32

标签: javascript angularjs

我对AngularJS很陌生。事实上,这是我的第一天。我在这里尝试做的是从我制作的控制器中获取数据并在视图中显示它。但我不知道为什么,它不仅仅是工作。

我的数据是学生名单。我所要做的就是按照列表顺序显示学生列表,并根据在文本框中输入的名称过滤列表。

我的代码非常简单:

<!DOCTYPE html>
<html ng-app>

  <head>
    <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  </head>

  <body>
    <h1>Hello!</h1>

      Student Name:
     <br />
      <input type="text" ng-model="sname" /> {{ sname }} 
    <div id="mvvm_communication" class="container" data-ng-controller="simpleController">

      <ul>
        <li ng-repeat="stud in students | filter:sname  | orderBy:'firstname'" >{{stud.firstname | lowercase }}, {{stud.lastname| uppercase }}</li>
      </ul>

    </div>

    <script>
      function simpleController($scope)
      {
        $scope.students=[
               {firstname:'Jordan',lastname:'Rains'},
               {firstname:'Michael',lastname:'Jordan'},
               {firstname:'John',lastname:'Doe'},
               {firstname:'John',lastname:'Smith'},
               {firstname:'Simcha',lastname:'Michelle'},
               {firstname:'Sydney',lastname:'Rivers'},
               {firstname:'Summer',lastname:'Rose'},
               {firstname:'Georgia',lastname:'Schubert'},
               {firstname:'Rosalie',lastname:'Fayadh'}
              ];

      }      
    </script>    
  </body>
</html>

这里是fiddle

3 个答案:

答案 0 :(得分:2)

您需要注册您的控制器!

var myApp = angular.module('myApp',[]);

myApp.controller('simpleController', ['$scope', simpleController]);

然后你还需要在ng-app中加上一个名字。

<html ng-app="myApp">

答案 1 :(得分:1)

我已更新了您的String

HTML:

<div ng-app="app">
  <div ng-controller="simpleController">
    <h1>Hello Student!</h1>   Student Name:<br/>
    <input type="text" ng-model="sname" /> {{ sname }} 
    <div id="mvvm_communication" class="container">
      <ul>
        <li ng-repeat="stud in students | filter:sname  | orderBy:'firstname'" >{{stud.firstname | lowercase }}, {{stud.lastname| uppercase }}</li>
      </ul>
    </div>
  </div>
</div>

角:

var app = angular.module('app', []);


app.controller('simpleController', function($scope) {

        $scope.students=[
               {firstname:'Jordan',lastname:'Rains'},
               {firstname:'Michael',lastname:'Jordan'},
               {firstname:'John',lastname:'Doe'},
               {firstname:'John',lastname:'Smith'},
               {firstname:'Simcha',lastname:'Michelle'},
               {firstname:'Sydney',lastname:'Rivers'},
               {firstname:'Summer',lastname:'Rose'},
               {firstname:'Georgia',lastname:'Schubert'},
               {firstname:'Rosalie',lastname:'Fayadh'}
              ]; 
});

答案 2 :(得分:1)

你需要定义一个角度模块:

      angular.module('app', []).controller('simpleController', simpleController);

请参阅jsFiddle