欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

学习AngularJS之Controller之概念理解之首篇

程序员文章站 2022-05-31 10:31:01
...
Controller 在 AngularJS 中是一个非常核心的概念。如何理解?

大家知道 AngularJS 是基于数据而对页面上对元素进行操作、互动的(双向绑定)。Controller 是谁的 Controller 呢?对,是页面上一个元素(作为数据对视图部分)的 Controller。页面上的元素是 Angular 的最小操作单元,是数据的视图层,是展示数据的模版,这个模版文件就要绑定一个 Controller 。


代码-模版部分
被标记了 ng-XXX 的元素,已不再是一个普通的元素,而是 angular 用来展示数据的视图层模版。
每一个模版,都要对应一个 Controller。
<head>
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
</head>

<body ng-app="myApp">

<table ng-controller="myApp-myCtrl-1" border="1">
	<tr ng-repeat="(key, value) in myObj">
		<td>Key - {{key}}</td>
		<td>Val - {{value}}</td>  
	</tr>
</table>

<div ng-controller="myApp-myCtrl-2">
	<div ng-repeat="record in records" class="item">
		{{$index}} - {{record}}
	</div>
</div>
</body>



代码:逻辑部分
var app = angular.module("myApp", []);

//This is my view controller 1 under my angular app!
app.controller("myApp-myCtrl-1", function($scope) {
  $scope.myObj = {
    "Name" : "Alfreds Futterkiste",
    "Country" : "Germany",
    "City" : "Berlin"
  }
});

//This is my view controller 2 under my angular app!
app.controller("myApp-myCtrl-2", function($scope) {
  $scope.records = [
    "Java",
    "C++",
    "Python",
    "Php",
  ]
});



学习AngularJS之Controller之概念理解之首篇
            
    
    博客分类: AngularJS AnguarJSControllerng-repeat 





完整代码:
在线测试:http://www.runoob.com/angularjs/ng-ng-repeat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
	.item{
		background-color:#eeeeaa;
		margin: 8px 0;
		padding: 15px 5px;
	}
	table{
		border-collapse:collapse;
	}
	td{
		background-color:#eeccee;
		padding: 15px 20px;
	}
</style>
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">

<table ng-controller="myApp-myCtrl-1" border="1">
	<tr ng-repeat="(key, value) in myObj">
		<td>Key - {{key}}</td>
		<td>Val - {{value}}</td>  
	</tr>
</table>

<div ng-controller="myApp-myCtrl-2">
	<div ng-repeat="record in records" class="item">
		{{$index}} - {{record}}
	</div>
</div>

<script>
var app = angular.module("myApp", []);

//This is my view controller 1 under my angular app!
app.controller("myApp-myCtrl-1", function($scope) {
  $scope.myObj = {
    "Name" : "Alfreds Futterkiste",
    "Country" : "Germany",
    "City" : "Berlin"
  }
});

//This is my view controller 2 under my angular app!
app.controller("myApp-myCtrl-2", function($scope) {
  $scope.records = [
    "Java",
    "C++",
    "Python",
    "Php",
  ]
});
	
</script>

</body>
</html>








转载请注明,
原文出处:http://lixh1986.iteye.com/admin/blogs/2427034

































-
  • 学习AngularJS之Controller之概念理解之首篇
            
    
    博客分类: AngularJS AnguarJSControllerng-repeat 
  • 大小: 40.8 KB