当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。