AngularJs基本篇 二 (控制器属性 + 控制器方法)

来源:互联网 发布:mac sumbline 注册码 编辑:程序博客网 时间:2024/06/07 00:16

1.控制器 

现在我们就用ng-controller指令来创建一个简单的控制器定义,如下所示:

<!DOCTYPE HTML><html><head><title> test </title><meta charset="utf-8"><script src="http://www.hubwiz.com/scripts/angular.min.js"></script></head><body><div ng-app="" ng-controller="Controller_test1">    Input Your Name:<input type="text" ng-model="chr.name">     <br/>    Hello,  Your Name is: <span ng-bind="chr.name"></span>     <br/>    </div>        <script>    function Controller_test1($scope) {       $scope.chr = {          name: "chr"       };    }    </script></body></html>

运行结果如下所示: 

Input Your Name: 
Hello, Your Name is: chr 

控制器的嵌套:

<!DOCTYPE HTML><html><head><title> test </title><meta charset="utf-8"><script src="http://www.hubwiz.com/scripts/angular.min.js"></script></head><body><div ng-app="" ng-controller="Controller_test1">    Input Your Name:<input type="text" ng-model="chr.name">     <br/>      <div ng-app="" ng-controller="Controller_test2">      Input Your Name2:<input type="text" ng-model="chr.name">       <br/>      Hello,  Your Name2 is: <span ng-bind="chr.name"></span>       <br/>      </div>        Hello,  Your Name is: <span ng-bind="chr.name"></span>     <br/>    </div>        <script>    function Controller_test1($scope) {       $scope.chr = {          name: "chr"       };    }    function Controller_test2($scope) {       $scope.chr = {          name: "chr2"       };    }    </script></body></html>
运行结果如下
Input Your Name: 

Input Your Name2: 
Hello, Your Name2 is: chr2 
Hello, Your Name is: chr 


2.控制器方法

自定义SayHi的方法 实现如下:

<!DOCTYPE HTML><html><head><title> 测试页 </title><meta charset="utf-8"><script src="http://www.hubwiz.com/scripts/angular.min.js"></script></head><body><div ng-app="" ng-controller="Controller_test">         Your name:         <input type="text" ng-model="username">         <button ng-click="sayHi()">打招呼</button>         <hr />         {{greeting}}    </div>    <script>    function Controller_test($scope) {      $scope.username = 'chr';      $scope.sayHi = function() {        $scope.greeting= 'Hi ' + $scope.username + '!';      };    }</script></body></html>

运行结果如下:

Your name:  


Hi chr!


1 0