Javascript 当使用ng模型时,将忽略select/dropdownlist上的AngularJS-Value属性
我的问题与此非常相似: 考虑到这一答案: 我想知道是否有办法对Javascript 当使用ng模型时,将忽略select/dropdownlist上的AngularJS-Value属性,javascript,asp.net,asp.net-mvc,angularjs,Javascript,Asp.net,Asp.net Mvc,Angularjs,我的问题与此非常相似: 考虑到这一答案: 我想知道是否有办法对进行同样的治疗 如果将ng型号设置为,则输入值将重置为null(因为角度) 下拉列表也有类似的行为。如果您在中设置了“选定选项”,则如果您还具有ng model属性,则该选项将被忽略 我是个新手,但我觉得这很烦人 由于我使用ASP MVC,如果我这样做,MVC已经定义了所有值: @Html.DropDownListFor(model => model.MyModel, new SelectList(/*...*/),
进行同样的治疗
如果将ng型号设置为
,则输入值将重置为null(因为角度)
下拉列表也有类似的行为。如果您在
中设置了“选定选项”,则如果您还具有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应该已经正确地完成了。是的,行为与输入相同,这就是“双向数据绑定”的工作方式
无论如何,您可以使用ng selected强制选择,例如:
在控制器中:
$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>
A.
B
C
但是请注意,这只会强制选择html,模型的值不会更新
在plunk上检查此项:
要了解更多数据绑定的工作原理,请参见:我最终使用了Angular.JS指令:
您可以在该博客中找到更多信息:
为了防止链接消失,您需要将此代码放在角度应用程序声明之前:
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>
var app=angular.module('myApp',['initialValue'])//将指令传递给应用程序
因此,您的意思是,在我创建模型时,如果不使用ng selected
属性,则无法说“请停止更改我下拉列表中的选定值”?因为这也会让人感觉像是做了两次工作。我不想编辑任何东西(除了我的JS中的一个函数,比如链接的SO帖子),因为MVC已经在我的下拉列表中设置了所选的值。。。