前端之家收集整理的这篇文章主要介绍了
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 属性。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <Meta charset="UTF-8">
- <title>Title</title>
- <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
- <script>
- angular.module("myApp",[]).controller("myControl",["$scope",function($scope){
- $scope.name = "哈哈哈";
- $scope.name1 = "大话西游2";
- $scope.fun = function(){
- alert($scope.name1);
- }
-
-
-
- $scope.fun = function(){
- var val = document.getElementById("val");
- // console.log("哈哈哈哈:" + val.value);
- alert(val.value);
-
- }
- }]);
- </script>
- <!--
- 在input中的值,若ng-model与ng-value都存在的话,则ng-value中值会被覆盖,显示ng-model中的值
- -->
- </head>
- <body >
- <div ng-app="myApp" ng-controller="myControl">
- <input type="text" id="val" ng-model="name" ng-value="name1" ng-blur="fun()" >
- {{name}}
- </div>
-
-
- </body>
- </html>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <Meta charset="UTF-8">
- <title>Title</title>
- <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
- <script>
- angular.module('valueExample',[])
- .controller('ExampleController',['$scope',function($scope) {
- $scope.names = ['pizza','unicorns','robots'];
- $scope.my = { favorite: 'unicorns' };
- }]);
- </script>
-
-
- </head>
- <body ng-app="valueExample" >
- <!--
- ng-repeat中使用value
- -->
- <form ng-controller="ExampleController">
- <h2>Which is your favorite?</h2>
- <label ng-repeat="name in names" for="{{name}}">
- {{name}}
- <input type="radio"
- ng-model="my.favorite"
- ng-value="name"
- id="{{name}}"
- name="favorite">
- </label>
- <div>You chose {{my.favorite}}</div>
- </form>
-
- </body>
- </html>