飙血推荐
  • HTML教程
  • MySQL教程
  • JavaScript基础教程
  • php入门教程
  • JavaScript正则表达式运用
  • Excel函数教程
  • UEditor使用文档
  • AngularJS教程
  • ThinkPHP5.0教程

AngularJS 控制器

时间:2021-11-22  作者:匿名  

AngularJS主要依赖于应用程序控制器控制的数据流的应用程序。 定义了一个控制器使用ng-controller指令。 一个控制器是一个JavaScript对象,其中包含属性/属性和功能。 每个控制器接受$scope参数范围,指的是应用程序/模块,控制器需要处理。

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

在这里,我们声明一个控制器命名studentController使用ng-controller指令。 我们定义如下

  <script>
 var mainApp = angular.module("mainApp", []);
 
 mainApp.controller('studentController', function($scope) {
$scope.student = {
   firstName: "王",
   lastName: "二",
   
   fullName: function() {
  var studentObject;
  studentObject = $scope.student;
  return studentObject.firstName + " " + studentObject.lastName;
   }
};
 });
  </script>

$scope studentController被定义为一个JavaScript对象作为参数范围。

$scope指的是应用程序,它使用studentController对象范围。

$scope的范围。 student studentController对象的一个属性。

$scope的firstName和lastName两个属性范围。 student对象。 我们将默认值传递给他们。

属性fullName是$scope的功能范围。 student对象,返回组合名称。

fullName函数,得到student对象,然后返回名称相结合。

请注意,我们还可以定义在一个单独的控制器对象JS文件和引用文件在HTML页面中。

现在我们可以使用studentController的student财产使用ng-model或使用表达式如下−

姓: <input type = "text" ng-model = "student.firstName"><br><br>
名: <input type = "text" ng-model = "student.lastName"><br>
<br>
你的姓名: {{student.fullName()}}

我们student。 firstName和student。 姓两个输入框。

我们结合student.fullName HTML ()。

现在只要你输入什么姓和名输入框,你可以看到全名得到自动更新。

例子

下面的示例展示了使用控制器

testAngularJS.htm

<html>
   
   <head>
      <title>Angular JS Controller</title>
      <script src = "https://www.yangzhiw.cn/static/js/angularjs-1.82/angular.min.js"></script>
   </head>
   
   <body>
      <h2>AngularJS控制器示例</h2>
      
  <div ng-app = "mainApp" ng-controller = "studentController">
 姓: <input type = "text" ng-model = "student.firstName"><br><br>
 名: <input type = "text" ng-model = "student.lastName"><br>
 <br>
 
 你的姓名: {{student.fullName()}}
  </div>
      
  <script>
 var mainApp = angular.module("mainApp", []);
 
 mainApp.controller('studentController', function($scope) {
$scope.student = {
   firstName: "王",
   lastName: "二",
   
   fullName: function() {
  var studentObject;
  studentObject = $scope.student;
  return studentObject.firstName + " " + studentObject.lastName;
   }
};
 });
  </script>
      
   </body>
</html>

输出

打开文件testAngularJS.htm在web浏览器并查看结果。

1637592054594211.png

搜你所爱
AngularJS:目录
湘ICP备14001474号-3  投诉建议:234161800@qq.com   部分内容来源于网络,如有侵权,请联系删除。