选择在编程指令AngularJS选择框中的空白选项 [英] Select the blank option of select box programmatically in AngularJS directive
问题描述
我有一个空白选项以及其他一些选项的选择框。该选项不能与ngOptions指令产生的,因为它们是在服务器端(与Symfony的形式)产生的。
在某些情况下,我要取消选择选择框的选择的值。使坯料选项被选中。但我不能得到这个工作。该选择框未更新。
我创建了一个的jsfiddle 显示问题。
HTML
< DIV NG控制器=MyCtrl>
<表格名称=形式>
<选择NG模型=foo.heroNAME =富[英雄]我-指令=>
<期权价值=>< /选项>
<期权价值=1>蝙蝠侠与LT; /选项>
<期权价值=2>超人LT; /选项>
<期权价值=3>&蜘蛛侠LT; /选项>
< /选择>
< /表及GT;
< P>选择:{{foo.hero}}< / P>
< / DIV>
的JavaScript
VAR对myApp = angular.module('对myApp',[]);功能MyCtrl($范围){
$ scope.foo = {英雄:'2'};
}myApp.directive('myDirective',函数($超时){
返回{
要求:['?形式'ngModel'],
链接:功能(范围,元素,ATTRS,ctlrs){
$超时(函数(){
变种modelController = ctlrs [0];
。modelController $ setViewValue('');
});
}
};
});
使用modelController。$渲染()调用$ setViewValue后。这将更新DOM元素(S)。
myApp.directive('myDirective',函数($超时){
返回{
要求:['?形式'ngModel'],
链接:功能(范围,元素,ATTRS,ctlrs){
$超时(函数(){
变种modelController = ctlrs [0];
。modelController $ setViewValue('');
。modelController $渲染();
});
}
};
});
更新小提琴 rel=\"nofollow\">。
I have a select box with a blank option and some other options. The options are not generated with ngOptions directive, because they are generated on server side (with Symfony forms).
In some cases I want to unselect the selected value of the select box. So that the blank option is selected. But I cannot get this to work. The select box does not get updated.
I have created a jsfiddle to show the problem.
html
<div ng-controller="MyCtrl">
<form name="form">
<select ng-model="foo.hero" name="foo[hero]" my-directive="">
<option value=""></option>
<option value="1">Batman</option>
<option value="2">Superman</option>
<option value="3">Spiderman</option>
</select>
</form>
<p>Selected: {{ foo.hero }}</p>
</div>
javascript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.foo = {hero: '2'};
}
myApp.directive('myDirective', function($timeout) {
return {
require: ['ngModel', '?form'],
link: function(scope, element, attrs, ctlrs) {
$timeout(function() {
var modelController = ctlrs[0];
modelController.$setViewValue('');
});
}
};
});
Use modelController.$render() after you call $setViewValue. This will update the DOM element(s).
myApp.directive('myDirective', function($timeout) {
return {
require: ['ngModel', '?form'],
link: function(scope, element, attrs, ctlrs) {
$timeout(function() {
var modelController = ctlrs[0];
modelController.$setViewValue('');
modelController.$render();
});
}
};
});
Updated fiddle here.
这篇关于选择在编程指令AngularJS选择框中的空白选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!