Home  >  Article  >  Web Front-end  >  Deep dive into views and directives in Angularjs

Deep dive into views and directives in Angularjs

青灯夜游
青灯夜游forward
2021-09-03 18:22:151296browse

This article will take you through the views and instructions in Angularjs, I hope it will be helpful to you!

Deep dive into views and directives in Angularjs

Introduction to AngularJS Views and Directives

In the first article you saw how AngularJS splits the application into views , Controller and Model (MVC). This article takes an in-depth look at how to create AngularJS views. [Related tutorial recommendations: "angular tutorial"]

Before starting, let me first set up a simple AngularJS application that you can use to experience the examples in this article:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

  <div ng-controller="MyController" >
      <span></span>
  </div>

  <script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
      //empty controller function
    });
  </script>

</body>
</html>

AngularJS Directives

AngularJS views mix data from the model into HTML templates. You can use AngularJSDirectives to tell AngularJS how to mix data into HTML templates. This article will cover the most commonly used AngularJS directives.

Interpolation directive

The interpolation directive is one of the most basic directives in AngujarJS. The interpolation directive inserts the result of an expression into an HTML template. You can use the {{ }} symbol to mark where you insert an expression. Here's an example:

<div ng-controller="MyController" >
    <span> {{myData.text}} </span>
</div>

HTML template is contained in a div element with the ng-controller attribute. Inside the HTML template is a span element, and inside is an interpolation instruction. This directive instructs AngularJSmyData.text to insert a data value at the given position.

The interpolation directive can also interpolate data returned from functions of the model object. Here is an example:

 <div ng-controller="MyController" >
      <span>{{myData.textf()}}</span>
  </div>

  <script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
      $scope.myData = {};
      $scope.myData.textf = function() { return "A text from a function"; };
    });
  </script>

In this example, the interpolation directive {{myData.textf()}} will be called on the model object myData.textf() function $scope and inserts the text returned from the function into the HTML template.

The textf() function is inserted into the $scope.myData object inside the controller function, as you can see in the example.

##ng-bind directive

The

ng-bind directive is a replacement for the interpolation directive. You can use it by ng-bind inserting an attribute in the HTML element where you want AngularJS to insert data. Here's an example:

<div ng-controller="MyController" >
  <span ng-bind="myData.textf()"></span>
</div>

This will insert the data returned by the

myData.text() function into the body of the span element. Please note that the ng-bind surrounding the expression within the attribute {{ }} is not required.

Escape HTML from the model

If the data obtained from the model contains HTML elements, these elements are escaped before being inserted into the HTML template. Escaping means that the HTML is displayed as text, not HTML.

This is done to prevent HTML injection attacks. For example, in a chat application, someone might

3f1c4e4b6b16bbbd69b2ee476dc4f83ainsert an element with JavaScript into the chat message. If this element is not escaped, anyone who sees the chat message may 3f1c4e4b6b16bbbd69b2ee476dc4f83aexecute the element. With HTML escaping, the 3f1c4e4b6b16bbbd69b2ee476dc4f83a element will appear as text only.

You can disable HTML escaping using the

ng-bind-html-unsafe directive as follows:

<div ng-controller="MyController" >
  <span ng-bind-html-unsafe="myData.textf()"></span>
</div>

You should be very careful when disabling HTML escaping . Make sure no untrusted HTML is displayed.

Conditional Rendering

AngularJS can show or hide HTML based on the state of data in the model. You can use a set of AngularJS directives created specifically for this purpose. I'll cover these directives in the following sections.

##ng-show ng-hide command

ng-show The

and ng-hide directives are used to show or hide HTML elements based on the data in the model. These two instructions do the same thing but are opposite to each other. Here are two examples: <pre class="brush:html;toolbar:false;"> &lt;div ng-controller=&quot;MyController&quot; &gt; &lt;span ng-show=&quot;myData.showIt&quot;&gt;&lt;/span&gt; &lt;span ng-hide=&quot;myData.showIt&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;script&gt; angular.module(&quot;myapp&quot;, []) .controller(&quot;MyController&quot;, function($scope) { $scope.myData = {}; $scope.myData.showIt = true; }); &lt;/script&gt;</pre>This example creates two

span

elements. One has a ng-show directive and the other has a ng-hide directive. Both directives look at the myData.showIt boolean variable to determine whether they should show or hide the span element. The ng-show directive will show the element if the model value is true, and hide the element if the model value is false. The ng-hide directive will do the opposite: span Hide the element if the model value is true, show it if the model value is false. <p>注意控制器函数如何将 设置<code>myData.showIttrue。这意味着上面的示例将显示第一个 span 元素并隐藏第二个。

HTML 元素(span在本例中为元素)使用 CSS 属性隐藏display: none;。这意味着 HTML 元素仍然存在于 DOM 中。它们只是不可见。

ng-switch 指令

ng-switch如果您想根据模型中的数据从 DOM 中添加或删除 HTML 元素,则使用 该指令。下面是一个例子:

<div ng-controller="MyController" >
    <div ng-switch on="myData.switch">
        <div ng-switch-when="1">Shown when switch is 1</div>
        <div ng-switch-when="2">Shown when switch is 2</div>
        <div ng-switch-default>Shown when switch is anything else than 1 and 2</div>
    </div>
</div>

<script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
      $scope.myData = {};
      $scope.myData.switch = 3;
    });
</script>

此示例包含一个div具有ng-switch属性和on属性的元素。该on属性指示要打开模型中的哪些数据。

div元素 内部是三个嵌套div元素。前两个嵌套div元素包含一个ng-switch-when属性。该属性的值告诉on父属性中引用的模型数据div应该具有什么值,以便嵌套div可见。在此示例中,第一个嵌套divmyData.switch为 1时可见,第二个嵌套divmyData.switch为 2时可见。

third嵌套div有一个ng-switch-default属性。如果没有其他ng-switch-when指令匹配,则显示div withng-switch-default属性。

在上面的示例中,控制器函数设置myData.switch为 3。这意味着将显示嵌套divng-switch-default属性。另外两个嵌套div元素将从 DOM 中完全删除。

ng-if 指令

ng-if指令可以包括/从DOM删除HTML元素,就像ng-switch指令,但它有一个简单的语法。下面是一个例子:

<div ng-controller="MyController" >
    <div ng-if="myData.showIt">ng-if Show it</div>
</div>

<script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
        $scope.myData = {};
        $scope.myData.showIt = true;
    });
</script>

ng-ifng-show+ 之间的主要区别ng-hide是 ng-if从 DOM 中完全删除 HTML 元素,而ng-showng-hide只是将 CSS 属性display: none;应用于元素。

ng-include 指令

ng-include指令可用于将来自其他文件的 HTML 片段包含到视图的 HTML 模板中。下面是一个例子:

<div ng-controller="MyController" >
    <div ng-include="&#39;angular-included-fragment.html&#39;"></div>
</div>

T此示例将文件包含angular-included-fragment.htmldiv具有ng-include属性的 HTML 模板内。注意文件名是如何引用的(单引号)。

您可以根据条件包含 HTML 片段。例如,您可以在两个文件之间进行选择,如下所示:

<div ng-controller="MyController" >
    <div ng-include="myData.showIt &&
                        &#39;fragment-1.html&#39; ||
                        &#39;fragment-2.html&#39;"></div>
</div>

<script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
        $scope.myData = {};
        $scope.myData.showIt = true;
    });
</script>

此示例将包括fragment-1.htmlifmyData.showIt为 true 和fragment-2.htmlifmyData.showIt为 false。

ng-repeat 指令

ng-repeat指令用于迭代一组项目并从中生成 HTML。在初始生成之后,ng-repeat监视用于生成 HTML 的项目的更改。如果项目发生变化,该ng-repeat指令可能会相应地更新 HTML。这包括重新排序和删除 DOM 节点。

这是一个简单的ng-repeat例子:

<ol>
   <li ng-repeat="theItem in myData.items">{{theItem.text}}</li>
</ol>

<script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
        $scope.myData = {};
        $scope.myData.items = [ {text : "one"}, {text : "two"}, {text : "three"} ];
    });
</script>

此示例将为数组中的li每个项目创建一个元素myData.items

您还可以迭代从函数调用返回的集合。下面是一个例子:

<ol>
   <li ng-repeat="theItem in myData.getItems()">{{theItem.text}}</li>
</ol>

<script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
        $scope.myData = {};
        $scope.myData.items = [ {text : "one"}, {text : "two"}, {text : "three"} ];
        $scope.myData.getItems = function() { return this.items; };
    });
</script>

您可以使用稍微不同的语法迭代 JavaScript 对象的属性:

<ol>
   <li ng-repeat="(name, value) in myData.myObject">{{name}} = {{value}}</li>
</ol>

<script>
    angular.module("myapp", [])
    .controller("MyController", function($scope) {
        $scope.myData = {};
        $scope.myData.myObject = { var1 : "val1", var2 : "val3", var3 : "val3"};
    });
</script>

注意指令的(name, value)部分ng-repeat。这会通知 AngularJS 迭代对象的属性。该name 参数将被绑定到的属性名称和value参数将被绑定到的属性值。该namevalue参数可以输出到HTML模板,就像任何其他JavaScript变量或对象的属性,你可以从上面的HTML模板见。

特殊的 ng-repeat 变量

ng-repeat指令定义了一组特殊变量,您可以在迭代集合时使用这些变量。这些变量是:

  • $index
  • $first
  • $中
  • $last

$index变量包含被迭代元素的索引。

$first$middle并且$last包含根据当前的项目是否正在迭代集合中的第一,中间或最后一个元素的布尔值。如果一个项目既不是第一个也不是最后一个,它就是“中间”。您可以使用这些变量使用例如生成不同的HTML ng-showng-hideng-switch, ng-ifng-include指令如前所述。

重复多个元素

到目前为止,您只看到了如何使用ng-repeat. 如果您想重复多个 HTML 元素,您必须将这些元素嵌套在容器元素中,并让容器元素具有该ng-repeat 元素,如下所示:

<div ng-repeat="(name, value) in myData.myObject">
   <div>{{name}}</li>
   <div>{{value}}</li>
</div>

但是,将要重复的元素包装在根元素中可能并不总是可行的。因此 AngularJS 有ng-repeat-startng-repeat-end指令,用于标记开始和结束重复的元素。下面是一个例子:

<ol>
    <li ng-repeat-start="(name, value) in myData.myObject">{{name}}</li>
    <li ng-repeat-end>{{value}}</li>
</ol>

此示例将为 中的li每个属性重复这两个元素 myData.myObject

过滤

上面介绍的一些指令支持过滤。本节将解释过滤的工作原理。

ng-repeat指令可以接受这样的过滤器:

<div ng-repeat="item in myData.items | filter: itemFilter"></div>

注意| filter: itemFilter上面声明的部分。那部分是过滤器定义。该| filter:部分告诉 AngularJS 将过滤器应用于 myData.items数组。该itemFilter是过滤函数的名称。此函数必须存在于$scope对象上,并且必须返回 true 或 false。如果过滤器函数返回 true,则ng-repeat指令使用数组中的元素。如果过滤器函数返回 false,则忽略该元素。下面是一个例子:

<script>
  angular.module("myapp", [])
    .controller("MyController", function($scope) {
      $scope.myData = {};
      $scope.myData.items  = [ {text : "one"}, {text : "two"}, {text : "three"}, {text : "four"} ];

      $scope.itemFilter = function(item) {
        if(item.text == "two") return false;
          return true;
        }
      }
    });
</script>

格式化过滤器

AngularJS 带有一组内置格式过滤器,可以与插值指令和ng-bind. 以下是格式过滤器的列表:

过滤器 说明
date 根据给定的日期格式将变量格式化为日期
currency 将变量格式化为带有货币符号的数字
number 将变量格式化为数字
lowercase 将变量转换为小写
uppercase 将变量转换为大写
json 将变量转换为 JSON 字符串

这是一个日期过滤器示例:

<span>{{myData.theDate | date: &#39;dd-MM-yyyy&#39;}}</span>

此示例显示了date可以根据| date: 部分后给出的日期格式模式格式化 JavaScript 日期对象的过滤器。它是myData.theDate 将被格式化为日期的属性。因此,它必须是一个 JavaScript 日期对象。

这是一个数字过滤器示例:

<span>{{myData.theNumber | number: 2}}</span>

此示例将myData.theNumber变量格式化为带有 2 个小数位的数字。

下面是一个小写和大写过滤器示例:

<span>{{myData.mixedCaseText | lowercase}}</span>
<span>{{myData.mixedCaseText | uppercase}}</span>

数组过滤器

AngularJS 还包含一组过滤或转换数组的数组过滤器。这些过滤器是:

数组过滤器:

过滤器 说明
limitTo 将数组限制为给定的大小,从数组中的某个索引开始。该limitTo过滤器也适用于字符串。
filter 通用过滤器。
orderBy 根据提供的条件对数组进行排序。

下面是一个limitTo例子:

<span>{{myData.theText | limitTo: 3}}</span>

这将$scope myData.theText变量限制为 3 个字符的长度。如果将此过滤器应用于数组,则该数组将被限制为 3 个元素。

filter过滤器是一种特殊的过滤器,可以做很多不同的事情。在最简单的形式中,它只是调用$scope对象上的函数。此函数必须返回trueor false。如果过滤器接受传递给它的值,则返回 True。如果过滤器不能接受该值,则返回 False。如果过滤器不能接受该值,则该值不包含在过滤产生的数组中。下面是一个例子:

<ol>
    <li ng-repeat="item in myData.items | filter:filterArray">
        {{item.text}} : {{$first}}, {{$middle}}, {{$last}}
    </li>
</ol>
<script>
    angular.module("myapp", [])
        .controller("MyController", function($scope) {
            $scope.myData = {};
            $scope.myData.items    = 
                [ {text : "one"}, {text : "two"}, {text : "three"}, {text : "four"} ];

            $scope.filterArray = function(item) {
                if(item.text == "two") return false;
                return true;
            }
        } );
</script>

此示例调用filterArray()过滤掉具有text值为的属性的项目 的函数two

下面是一个orderBy例子:

<ol>
    <li ng-repeat="item in myData.items | orderBy:sortField:reverse">
        {{item.text}} : {{$first}}, {{$middle}}, {{$last}}
    </li>
</ol>
    
<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope) {
                $scope.myData = {};
                $scope.myData.items    = [ {text : "one"}, {text : "two"}, {text : "three"}, {text : "four"} ];
                $scope.sortField = "text";
                $scope.reverse   = true;
            } );
</script>

所述orderBy过滤器可以接受一个$scope变量作为参数。在此示例中,该变量名为sortField。此变量的值是已排序数据对象的属性名称,用于对数据对象进行排序。在此示例中,sortField 属性设置为text这意味着数据对象的text属性用于对数据对象进行排序。

orderBy过滤器还可以采取的第二$scope变量作为参数。在此示例中,该变量名为reverse。该变量的值决定了数据对象是按自然顺序排序,还是按自然顺序排序。在这种情况下,reverse变量设置为true,这意味着数据对象将按相反顺序排序。

链接过滤器

可以通过简单地在过滤器部分中一个接一个地放置更多过滤器来链接过滤器。链接过滤器时,一个过滤器的输出用作链中下一个过滤器的输入。下面是一个例子:

<span>{{myData.theText | limitTo: 5 | uppercase}}</span>

此示例首先myData.theText使用limitTo过滤器将字符串限制为 5 个字符,然后使用 过滤器将 5 个字符转换为大写uppercase 。

将过滤器输出分配给变量

可以将过滤器的输出分配给一个临时变量,然后您可以稍后在视图中引用该变量。下面是一个例子:

<ol>
    <li ng-repeat="item in filteredItems = ( myData.items | filter:filterArray) ">
        {{item.text}} : {{$first}}, {{$middle}}, {{$last}}
    </li>
</ol>
<div>{{filteredItems.length}}</div>

此示例将过滤的输出分配给filteredItems变量。该示例然后{{ }}ol元素下的指令内引用此变量。

实现自定义过滤器

如果 AngularJS 过滤器不适合您的需要,您可以实现自己的过滤器。下面是一个例子:

<div>Filtered: {{myData.text | myFilter}}</div>
    
    
<script>
    var module = angular.module("myapp", []);

    module.filter(&#39;myFilter&#39;, function() {

        return function(stringValue) {
            return stringValue.substring(0,3);
        };
    });
</script>

此示例向 AngularJS 注册了一个过滤器,它可以过滤字符串。过滤器返回字符串的前 3 个字符。过滤器以 name 注册myFilter。正如您在过滤器开头看到的那样,您在引用过滤器时必须使用该名称。

如果您的过滤器需要更多的输入参数,请在过滤器函数中添加更多参数,并在过滤器名称和:引用它时添加参数。下面是一个例子:

<div>Filtered: {{myData.text | myFilter :2:5}}</div>

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

    module.filter(&#39;myFilter&#39;, function() {

        return function(stringValue, startIndex, endIndex) {
            return stringValue.substring(parseInt(startIndex), parseInt(endIndex));
        };
    });
</script>

注意过滤器引用 ( | myfilter:2:5) 现在在过滤器名称后面有两个值,每个值用冒号分隔。这两个值作为参数传递给过滤器。还要注意 filter 函数现在如何接受两个名为startIndex和 的额外参数endIndex。这两个参数用于确定字符串的哪一部分作为子字符串从过滤器返回

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Deep dive into views and directives in Angularjs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete