ng-model与ng-value的区别

前端之家收集整理的这篇文章主要介绍了ng-model与ng-value的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
首先,先了解这两个属性是什么作用,ng-model是数据的双向绑定,ng-value官网上的解释: AngularJS expression,whose value will be bound to the value attribute and value property of the element. It is especially useful for dynamically generated lists using ngRepeat.意思就是指令用于设置 input 或 select 元素的 value 属性

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <Meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
  7. <script>
  8. angular.module("myApp",[]).controller("myControl",["$scope",function($scope){
  9. $scope.name = "哈哈哈";
  10. $scope.name1 = "大话西游2";
  11. $scope.fun = function(){
  12. alert($scope.name1);
  13. }
  14.  
  15.  
  16.  
  17. $scope.fun = function(){
  18. var val = document.getElementById("val");
  19. // console.log("哈哈哈哈:" + val.value);
  20. alert(val.value);
  21.  
  22. }
  23. }]);
  24. </script>
  25. <!--
  26. 在input中的值,若ng-model与ng-value都存在的话,则ng-value中值会被覆盖,显示ng-model中的值
  27. -->
  28. </head>
  29. <body >
  30. <div ng-app="myApp" ng-controller="myControl">
  31. <input type="text" id="val" ng-model="name" ng-value="name1" ng-blur="fun()" >
  32. {{name}}
  33. </div>
  34.  
  35.  
  36. </body>
  37. </html>

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <Meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
  7. <script>
  8. angular.module('valueExample',[])
  9. .controller('ExampleController',['$scope',function($scope) {
  10. $scope.names = ['pizza','unicorns','robots'];
  11. $scope.my = { favorite: 'unicorns' };
  12. }]);
  13. </script>
  14.  
  15.  
  16. </head>
  17. <body ng-app="valueExample" >
  18. <!--
  19. ng-repeat中使用value
  20. -->
  21. <form ng-controller="ExampleController">
  22. <h2>Which is your favorite?</h2>
  23. <label ng-repeat="name in names" for="{{name}}">
  24. {{name}}
  25. <input type="radio"
  26. ng-model="my.favorite"
  27. ng-value="name"
  28. id="{{name}}"
  29. name="favorite">
  30. </label>
  31. <div>You chose {{my.favorite}}</div>
  32. </form>
  33.  
  34. </body>
  35. </html>

猜你在找的Angularjs相关文章