<!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>databinding3</title> </head> <body> <div ng-controller='dataCtrl' ng-bind-template='{{data1}}爱{{data2}} '> </div> <script type="text/javascript" src="https://www.jb51.net/node_modules/angular/angular.min.js"></script> <script type="text/javascript"> angular.module('myApp',[]) .controller('dataCtrl',function($scope,$sce){ $scope.data1 = "我"; $scope.data2 = "中国"; }) </script> </body> </html> <!-- 我爱中国-->
5、ng-non-bindable
有时我们使用了{{}}但是我们并不是要绑定数据,直接用会出错,所以要像这样
<!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>databinding1</title> </head> <body> <h1 ng-controller='dataCtrl' ng-non-bindable> ng中绑定数据的方法是{{data}} </h1> <script type="text/javascript" src="https://www.jb51.net/node_modules/angular/angular.min.js"></script> <script type="text/javascript"> angular.module('myApp',[]) .controller('dataCtrl',function($scope){ //$scope.data = "你好啊!"; }) </script> </body> </html>
6、双向数据绑定ng-model
双向数据绑定允许元素从用户处收集数据以改变程序状态。
<!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>databinding5</title> </head> <body> <div ng-controller='dataCtrl'> <h1>{{data}}</h1> <input type="text" ng-model="data"> </div> <script type="text/javascript" src="https://www.jb51.net/node_modules/angular/angular.min.js"></script> <script type="text/javascript"> angular.module('myApp',[]) .controller('dataCtrl',function($scope){ $scope.data = "你好啊!"; }) </script> </body> </html>
你会发现文本框的内容和h1中的内容同步变化。
7、小结一下
与数据绑定的相关指令如下