了解AngularJS中控制器的基础知识

时间:2018-06-10 16:12:13

标签: angularjs angularjs-scope

我仍然非常基本使用AngularJS(和老实说编程一样。在线观看了一些视频,我试图通过下面的例子来理解控制器概念(例如传递一个数组,然后用ng迭代它) -repeat)。过去一小时已经过了这个,它没有控制器(例如数组),但是在单独的脚本中添加数组时没有。任何人都可以帮助我在逻辑中找到我的错误 - 它字面上是和视频一样,但是我看不到错误(甚至是错字),觉得这是非常重要的,我应该让它工作,然后继续下一步。

非常感谢您的任何帮助:

<html ng-app>
<head><title>My First Page</title></head>
<body >
<div class="container" ng-controller="SimpleController">
    Name:
    <br />
    <input type="text" ng-model="name" />
    <br />    
    <ul>
        <li ng-repeat="cust in customers"> {{ cust.name }} </li>
    </ul>
</div>
<script src="script/angular.min.js"></script> 
<script>
    function SimpleController($scope) {
$scope.customers = [
    { name: 'Simon', lastname: 'Test' },
    { name: 'Thomas', lastname: 'Testi' },
    { name: 'Adi', lastname: 'Testo' },
    { name: 'Adrian', lastname: 'Testo' },
    { name: 'Tomeli', lastname: 'Testi' }
];
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您正在使用具有角度1.1版本的控制器的全局声明。如果使用的版本高于1.3,则应按如下方式声明控制器,

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
  $scope.customers = [
    { name: 'Simon', lastname: 'Test' },
    { name: 'Thomas', lastname: 'Testi' },
    { name: 'Adi', lastname: 'Testo' },
    { name: 'Adrian', lastname: 'Testo' },
    { name: 'Tomeli', lastname: 'Testi' }
];
});

<强>样本

var app = angular.module('testApp',[]);
app.controller('SimpleController',function($scope){
  $scope.customers = [
    { name: 'Simon', lastname: 'Test' },
    { name: 'Thomas', lastname: 'Testi' },
    { name: 'Adi', lastname: 'Testo' },
    { name: 'Adrian', lastname: 'Testo' },
    { name: 'Tomeli', lastname: 'Testi' }
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp">
 <div class="container" ng-controller="SimpleController">
    Name:
    <br />
    <input type="text" ng-model="name" />
    <br />    
    <ul>
        <li ng-repeat="cust in customers"> {{ cust.name }} </li>
    </ul>
</div>
</body>