(二)用控制器controller给模型数据赋初始值

之前博客,非常easy的就实现了模型数据和页面显示的自己主动绑定。如今我们使用控制器,给模型赋初始值。

假设使用jquery来实现变量赋初值,须要在页面载入完毕后运行$("#target").attr("value",selfValue);使用AngularJS代码例如以下:

<!doctype html>  
<html lang="en" ng-app>  
    <head>  
       <meta charset="utf-8">  
       <title>Hello,World!</title>  
       <script src="angular1.2.25.js"></script>  
	   <script>
	   
	   function WholeController($scope)
	   {
		$scope.yourName = "aty";
	   }
	   </script>
    </head>  
    <body ng-controller="WholeController">  
        <input type="text" ng-model="yourName">  
        <h1>Hello, {{yourName}}</h1>  
    </body>  
</html> 

这里须要注意:函数名必须与ng-controller中的名称一致,函数的參数$scope名次也是固定的,不能随便改动。这种话。AngularJS框架会自己主动运行我们的控制器,并将作用域对象注入到函数參数。

非常显然这种方式非常不好,由于不能改变函数參数名,后面我会看到还有别的方式来达到相同的目的。兴许我们再继续学习。能够看到Controller就是一个JavaScript 函数,在 Angular 里,当这个函数通过 ng-controller 指令绑定到 DOM 上的时候,这个函数就是 Controller 了。我们能够为 Controller Scope 对象。

原文地址:https://www.cnblogs.com/yxysuanfa/p/6718046.html