當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


AngularJS ng-bind用法及代碼示例


AngularJS中的ng-bind指令用於將任何特定HTML元素的文本內容綁定/替換為在給定表達式中輸入的值。隻要表達式的值在ng-bind指令中發生更改,指定的HTML內容的值就會更新。

用法:

<element ng-bind="expression"> Contents... </element>

其中,表達式用於指定要求值的表達式或變量。


範例1:本示例使用ng-bind指令將兩個數字的乘積綁定到<span>元素。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-checked Directive</title> 
  
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
  
<body ng-app="gfg" style="text-align:center"> 
      
    <h1 style="color:green">GeeksforGeeks</h1> 
    <h2>ng-bind Directive</h2>         
      
    <div ng-controller="app"> 
        num1:<input type="number" ng-model="num1"
                ng-change="product()" /> 
        <br><br> 
          
        num2:<input type="number" ng-model="num2"
                ng-change="product()" /> 
        <br><br> 
          
        <b>Product:</b> <span ng-bind="result"></span> 
    </div> 
      
    <script> 
        var app = angular.module("gfg", []); 
        app.controller('app', ['$scope', function ($app) { 
            $app.num1 = 1; 
            $app.num2 = 1; 
            $app.product = function () { 
                $app.result = ($app.num1 * $app.num2); 
            } 
        }]); 
    </script> 
</body> 
  
</html>

輸出:
ng-bind

範例2:本示例使用ng-bind指令將<span>元素的innerHTML綁定到變量文本。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title>ng-checked Directive</title> 
  
    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
    </script> 
</head> 
  
<body  style = "text-align:center"> 
      
    <h1 style = "color:green">GeeksforGeeks 
    <h2 style = "">ng-bind directive</h2> 
      
    <div ng-app="" ng-init="txt='GeeksforGeeks';col='green'"> 
        <div> 
            <span ng-bind="txt"></span> is the 
            computer science portal for geeks. 
        </div> 
    </div> 
</body> 
  
</html>

輸出:
ng-bind



相關用法


注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 AngularJS | ng-bind Directive。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。