Javascript AngularJS - 当使用 ng-model 时,输入文本框上的 Value 属性会被忽略吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10610282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?
提问by HelloWorld
Using AngularJS if I set a simple input text box value to something like "bob" below. The value does not display if the ng-model
attribute is added.
如果我将一个简单的输入文本框值设置为类似于下面的“bob”,则使用 AngularJS。如果ng-model
添加了属性,则不会显示该值。
<input type="text"
id="rootFolder"
ng-model="rootFolders"
disabled="disabled"
value="Bob"
size="40"/>
Anyone know of a simple work around to default this input to something and keep the ng-model
? I tried to use a ng-bind
with the default value but that seems not to work either.
任何人都知道一个简单的解决方法可以将此输入默认为某些内容并保留ng-model
? 我尝试将 ang-bind
与默认值一起使用,但这似乎也不起作用。
回答by Vojta
That's desired behavior, you should define the model in the controller, not in the view.
这是所需的行为,您应该在控制器中而不是在视图中定义模型。
<div ng-controller="Main">
<input type="text" ng-model="rootFolders">
</div>
function Main($scope) {
$scope.rootFolders = 'bob';
}
回答by Mark Rajcok
Vojta described the "Angular way", but if you really need to make this work, @urbanek recently posted a workaround using ng-init:
Vojta 描述了“Angular 方式”,但如果你真的需要让它工作,@urbanek 最近发布了一个使用 ng-init 的解决方法:
<input type="text" ng-model="rootFolders" ng-init="rootFolders='Bob'" value="Bob">
https://groups.google.com/d/msg/angular/Hn3eztNHFXw/wk3HyOl9fhcJ
https://groups.google.com/d/msg/angular/Hn3eztNHFXw/wk3HyOl9fhcJ
回答by Ivan Breet
Overriding the input directive does seem to do the job. I made some minor alterations to Dan Hunsaker's code:
覆盖输入指令似乎确实可以完成这项工作。我对Dan Hunsaker的代码做了一些小改动:
- Added a check for ngModel before trying to use
$parse().assign()
on fields without a ngModel attributes. - Corrected the
assign()
function param order.
- 在尝试
$parse().assign()
在没有 ngModel 属性的字段上使用之前添加了对 ngModel 的检查。 - 更正了
assign()
函数参数顺序。
app.directive('input', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if (attrs.ngModel && attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
});
回答by superluminary
The Angular way
角度方式
The correct Angular way to do this is to write a single page app, AJAX in the form template, then populate it dynamically from the model. The model is not populated from the form by default because the model is the single source of truth. Instead Angular will go the other way and try to populate the form from the model.
正确的 Angular 方法是在表单模板中编写一个单页应用程序,AJAX,然后从模型动态填充它。默认情况下不会从表单填充模型,因为模型是唯一的真实来源。相反,Angular 会走另一条路并尝试从模型填充表单。
If however, you don't have time to start over from scratch
但是,如果您没有时间从头开始
If you have an app written, this might involve some fairly hefty architectural changes. If you're trying to use Angular to enhance an existing form, rather than constructing an entire single page app from scratch, you can pull the value from the form and store it in the scope at link time using a directive. Angular will then bind the value in the scope back to the form and keep it in sync.
如果您编写了一个应用程序,这可能涉及一些相当大的架构更改。如果您尝试使用 Angular 来增强现有表单,而不是从头开始构建整个单页应用程序,您可以从表单中提取值并在链接时使用指令将其存储在作用域中。然后 Angular 会将作用域中的值绑定回表单并保持同步。
Using a directive
使用指令
You can use a relatively simple directive to pull the value from the form and load it in to the current scope. Here I've defined an initFromForm directive.
您可以使用相对简单的指令从表单中提取值并将其加载到当前作用域中。这里我定义了一个 initFromForm 指令。
var myApp = angular.module("myApp", ['initFromForm']);
angular.module('initFromForm', [])
.directive("initFromForm", function ($parse) {
return {
link: function (scope, element, attrs) {
var attr = attrs.initFromForm || attrs.ngModel || element.attrs('name'),
val = attrs.value;
if (attrs.type === "number") {val = parseInt(val)}
$parse(attr).assign(scope, val);
}
};
});
You can see I've defined a couple of fallbacks to get a model name. You can use this directive in conjunction with the ngModel directive, or bind to something other than $scope if you prefer.
你可以看到我定义了几个后备来获取模型名称。您可以将此指令与 ngModel 指令结合使用,或者如果您愿意,可以绑定到 $scope 以外的其他内容。
Use it like this:
像这样使用它:
<input name="test" ng-model="toaster.test" value="hello" init-from-form />
{{toaster.test}}
Note this will also work with textareas, and select dropdowns.
请注意,这也适用于 textareas,并选择下拉列表。
<textarea name="test" ng-model="toaster.test" init-from-form>hello</textarea>
{{toaster.test}}
回答by Dan Hunsaker
Update:My original answer involved having the controller contain DOM-aware code, which breaks Angular conventions in favor of HTML. @dmackerman mentioned directives in a comment on my answer, and I completely missed that until just now. With that input, here's the rightway to do this without breaking Angular orHTML conventions:
更新:我的原始答案涉及让控制器包含 DOM 感知代码,这打破了支持 HTML 的 Angular 约定。@dmackerman 在对我的回答的评论中提到了指令,直到现在我才完全错过。使用该输入,这是在不破坏 Angular或HTML 约定的情况下执行此操作的正确方法:
There's also a way to get both - grab the value of the element and use that to update the model in a directive:
还有一种方法可以获得两者 - 获取元素的值并使用它来更新指令中的模型:
<div ng-controller="Main">
<input type="text" id="rootFolder" ng-model="rootFolders" disabled="disabled" value="Bob" size="40" />
</div>
and then:
进而:
app.directive('input', ['$parse', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if(attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
}]);
You can of course modify the above directive to do more with the value
attribute before setting the model to its value, including using $parse(attrs.value, scope)
to treat the value
attribute as an Angular expression (though I'd probably use a different [custom] attribute for that, personally, so the standard HTML attributes are consistently treated as constants).
您当然可以修改上述指令以value
在将模型设置为其值之前对属性执行更多操作,包括使用$parse(attrs.value, scope)
将value
属性视为 Angular 表达式(尽管我个人可能会为此使用不同的 [custom] 属性,因此标准 HTML 属性始终被视为常量)。
Also, there is a similar question over at Making data templated in available to ng-modelwhich may also be of interest.
此外,在Make data templated in available to ng-model中也有一个类似的问题,这也可能很有趣。
回答by Hazarapet Tunanyan
If you use AngularJs ngModel directive, remember that the value of value
attribute does not bind on ngModel field.You have to init it by yourself and the best way to do it,is
如果您使用 AngularJs ngModel 指令,请记住value
属性的值不会绑定在 ngModel 字段上。您必须自己初始化它,最好的方法是
<input type="text"
id="rootFolder"
ng-init="rootFolders = 'Bob'"
ng-model="rootFolders"
disabled="disabled"
value="Bob"
size="40"/>
回答by dale.lotts
This is a slight modification to the earlier answers...
这是对早期答案的轻微修改......
There is no need for $parse
不需要 $parse
angular.directive('input', [function () {
'use strict';
var directiveDefinitionObject = {
restrict: 'E',
require: '?ngModel',
link: function postLink(scope, iElement, iAttrs, ngModelController) {
if (iAttrs.value && ngModelController) {
ngModelController.$setViewValue(iAttrs.value);
}
}
};
return directiveDefinitionObject;
}]);
回答by Bhaskar Bhatt
Hi you can try below methods with initialize of model.
嗨,您可以尝试以下方法初始化模型。
Here you can initialize ng-model of textbox two way
在这里您可以通过两种方式初始化文本框的 ng-model
- With use of ng-init
- 使用 ng-init
- With use of $scope in js
- 在 js 中使用 $scope
<!doctype html>
<html >
<head>
<title>Angular js initalize with ng-init and scope</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="app" >
<h3>Initialize value with ng-init</h3>
<!-- Initlialize model values with ng-init -->
<div ng-init="user={fullname:'Bhaskar Bhatt',email:'[email protected]',address:'Ahmedabad'};">
Name : <input type="text" ng-model="user.fullname" /><br/>
Email : <input type="text" ng-model="user.email" /><br/>
Address:<input type="text" ng-model="user.address" /><br/>
</div>
<!-- initialize with js controller scope -->
<h3>Initialize with js controller</h3>
<div ng-controller="alpha">
Age:<input type="text" name="age" ng-model="user.age" /><br/>
Experience : <input type="text" name="experience" ng-model="user.exp" /><br/>
Skills : <input type="text" name="skills" ng-model="user.skills" /><br/>
</div>
</body>
<script type="text/javascript">
angular.module("app",[])
.controller("alpha",function($scope){
$scope.user={};
$scope.user.age=27;
$scope.user.exp="4+ years";
$scope.user.skills="Php,javascript,Jquery,Ajax,Mysql";
});
</script>
</html>
回答by sg28
The issue is that you have to set the ng-model to the parent element to where you want to set the ng-value/value . As mentioned by Angular:
问题是您必须将 ng-model 设置为要设置 ng-value/value 的父元素。正如 Angular 所提到的:
It is mainly used on input[radio] and option elements, so that when the element is selected, the ngModel of that element (or its select parent element) is set to the bound value.
它主要用于 input[radio] 和 option 元素,以便在选择元素时,将该元素(或其选择父元素)的 ngModel 设置为绑定值。
Eg:This is an executed code :
例如:这是一个执行的代码:
<div class="col-xs-12 select-checkbox" >
<label style="width: 18em;" ng-model="vm.settingsObj.MarketPeers">
<input name="radioClick" type="radio" ng-click="vm.setPeerGrp('market');"
ng-value="vm.settingsObj.MarketPeers"
style="position:absolute;margin-left: 9px;">
<div style="margin-left: 35px;color: #717171e8;border-bottom: 0.5px solid #e2e2e2;padding-bottom: 2%;">Hello World</div>
</label>
</div>
Note: In this above case I alreday had the JSON response to the ng-model and the value, I am just adding another property to the JS object as "MarketPeers". So the model and value may depend according to the need, but I think this process will help, to have both ng-model and value but not having them on the same element.
注意:在上面的例子中,我已经收到了对 ng-model 和值的 JSON 响应,我只是将另一个属性添加到 JS 对象中作为“MarketPeers”。所以模型和值可能取决于需要,但我认为这个过程会有所帮助,同时拥有 ng-model 和值,但不要将它们放在同一个元素上。
回答by tkrloltkr
I had similar issue. I was not able to use value="something"
to display and edit.
I had to use the below command inside my <input>
along withe ng model being declared.
我有类似的问题。我无法value="something"
用于显示和编辑。我必须在声明中使用以下命令<input>
和 ng 模型。
[(ngModel)]=userDataToPass.pinCode
Where I have the list of data in the object userDataToPass
and the item that I need to display and edit is pinCode
.
我在哪里有对象中的数据列表userDataToPass
,我需要显示和编辑的项目是pinCode
.
For the same , I referred to this YouTube video
同样,我参考了这个 YouTube 视频