加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

简述AngularJS的控制器的使用

发布时间:2020-12-14 22:20:33 所属栏目:资源 来源:网络整理
导读:AngularJS应用主要依赖于控制器来控制数据在应用程序中的流动。控制器采用ng-controller指令定义。控制器是一个包含属性/属性和JavaScript对象的功能。每个控制器接受$scope参数指定应用程序/模块,由控制器控制。 div ng-app="" ng-controller="studentCont

 AngularJS应用主要依赖于控制器来控制数据在应用程序中的流动。控制器采用ng-controller指令定义。控制器是一个包含属性/属性和JavaScript对象的功能。每个控制器接受$scope参数指定应用程序/模块,由控制器控制。

<div ng-app="" ng-controller="studentController">
...
</div>

在这里,我们已经声明采用ng-controller指令的控制器studentController。作为下一步,我们将定义studentController如下

    <script>
    function studentController($scope) {
      $scope.student = {
       firstName: "yiibai",lastName: "com",fullName: function() {
         var studentObject;
         studentObject = $scope.student;
         return studentObject.firstName + " " + studentObject.lastName;
       }
      };
    }
    </script>
    
    
  •     studentController 定义 $scope 作为JavaScript对象参数。
  •     $scope 表示应用程序,使用studentController对象。
  •     $scope.student 是studentController对象的属性。
  •     firstName和lastName是$scope.student 对象的两个属性。我们已经通过了默认值给他们。
  •     fullName 是$scope.student对象的函数,它的任务是返回合并的名称。
  •     在fullName函数中,我们现在要学生对象返回组合的名字。
  •     作为一个说明,还可以定义控制器对象在单独的JS文件,并把有关文件中的HTML页面。

现在可以使用ng-model或使用表达式如下使用studentController学生的属性。

    Enter first name: <input type="text" ng-model="student.firstName"><br>
    Enter last name: <input type="text" ng-model="student.lastName"><br>
    <br>
    You are entering: {{student.fullName()}}
    
    
  •     现在有 student.firstName 和 student.lastname 两个输入框。
  •     现在有 student.fullName()方法添加到HTML。
  •     现在,只要输入first name和lastname输入框中输入什么,可以看到两个名称自动更新。

例子

下面的例子将展示使用控制器。
testAngularJS.html 文件内容如下:

<html>
<head>
<title>Angular JS Controller</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">

Enter first name: <input type="text" ng-model="student.firstName"><br><br>
Enter last name: <input type="text" ng-model="student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
function studentController($scope) {
  $scope.student = {
   firstName: "Mahesh",lastName: "Parashar",fullName: function() {
     var studentObject;
     studentObject = $scope.student;
     return studentObject.firstName + " " + studentObject.lastName;
   }
  };
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

输出

在Web浏览器打开textAngularJS.html,看到以下结果:

2015616120726250.png (679×365)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读