我的问题非常类似于这个问题:AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?
考虑到这个答案:https://stackoverflow.com/a/20522955/1598891
我想知道是否有办法对<select>
进行同样的治疗?
如果将ng-model
设置为<input type="text">
,则将输入的值重置为null (由于角度)。
下拉列表也有类似的行为。如果您在<select>
中设置了"selected“,如果您也具有ng-model
属性,它将被忽略。
我对角很陌生,但我觉得这很烦人。
由于我使用的是ASP.MVC,如果我这样做,MVC已经定义了所有的值:
@Html.DropDownListFor(model => model.MyModel,
new SelectList(/*...*/),
"Select an options",
new { @class = "form-control",
ng_model = "MyModelProperty"})
我知道我可以这样做:
ng_model = @String.Format("myModel = {0}", Model.MyModelProperty)
但是重复这些信息会有些烦人,因为MVC应该已经做好了。
发布于 2014-12-02 14:47:01
我最后使用了这个Angular.JS指令:
https://github.com/glaucocustodio/angular-initial-value
你可以在博客中找到更多的信息:
http://blog.glaucocustodio.com/2014/10/20/init-ng-model-from-form-fields-attributes/
为了防止链接失效,您需要将此代码放在角应用程序声明之前:
var initialValueModule = angular.module('initialValue', [])
.directive('initialValue', function() {
return{
restrict: 'A',
controller: ['$scope', '$element', '$attrs', '$parse', function($scope, $element, $attrs, $parse){
var getter, setter, val, tag;
tag = $element[0].tagName.toLowerCase();
val = $attrs.initialValue || $element.val();
if(tag === 'input'){
if($element.attr('type') === 'checkbox'){
val = $element[0].checked ? true : undefined;
} else if($element.attr('type') === 'radio'){
val = ($element[0].checked || $element.attr('selected') !== undefined) ? $element.val() : undefined;
}
}
if($attrs.ngModel){
getter = $parse($attrs.ngModel);
setter = getter.assign;
setter($scope, val);
}
}]
};
});
/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
module.exports = initialValueModule;
}
然后你就可以:
<script>
var app = angular.module('myApp', ['initialValue']); //Pass the directive to the app
</script>
<body ng-app="myApp">
<!-- Add the "initial-value" directive to the html input -->
<input type="text" value="John" name="text" initial-value ng-model="text" id="text"/>
</body>
发布于 2014-11-29 13:56:24
是的,行为和输入是一样的,这就是“双向数据绑定”的工作方式。
无论如何,您可以使用ng选择强制进行选择,例如:
在您的控制器中:
$scope.selected = null;
在html中:
<select ng-model="model.selected">
<option value="a">a</option>
<option value="b" ng-selected="true">b</option>
<option value="c">c</option>
</select>
但是请注意,这只会强制在html上选择,模型的值不会被更新
在plunk上检查这个:http://plnkr.co/edit/uV3md09CYX0mUVfIy4b2
要了解数据绑定的更多工作方式,请参见以下内容:ng-selected not working in select element
https://stackoverflow.com/questions/27199031
复制相似问题