AngularJS 指令绑定输入
AngularJS Directive binding input
当具有变量输入类型复选框时,值设置不正确。
简化此代码以解决问题。
controller.coffee
angular.module 'tinyhandsAmenApp'
.controller 'TestrouteCtrl', ($scope) ->
@user =
admin: true
directive.coffee
angular.module 'tinyhandsAmenApp'
.directive 'formInput', ->
restrict: 'EA'
scope:
model: '='
template: '<input ng-model="model" type="{{ type }}"/>'
link: (scope, element, attrs) ->
scope.type = "checkbox"
example.html
<div class="col-md-12" ng-controller="TestrouteCtrl as tr">
<input type="checkbox" ng-model="tr.user.admin" />
<form-input model="tr.user.admin"></form-input>
</div>
结果 html 有 value="true"
这使得 Angluar 似乎将其视为文本框。如果我用 checkbox
替换 {{ type }}
那么它就可以了。指令中的输入和输出都设置正确。
我还发现如果我将指令 html 更改为
<form-input model="tr.user.admin" type="checkbox"></form-input>
指令js中的作用域对象为
scope:
model: '='
type: '@'
并从 link 函数中删除 scope.type = "checkbox"
它起作用了!
所以看起来 Angluar 在调用 link 之前使用 ng-model 设置输入元素的值。这有意义吗?
我想这个解决方案现在已经足够好了,但我真的很想能够从 js 中指定输入类型。
顺便说一下,如果类型是文本,我原来的方式就可以正常工作。
更新: 这里有一个 JSFiddle 说明了我在说什么。 form-input
不起作用。 form-input2
确实如此,但在 html.
中的指令上使用了 type 属性
UPDATE2: 我想做的是在 javascript 中指定输入类型并绑定到控制器。
您正在尝试做的事情无法完成。关于原因的简短回答是:Internet Explorer 不支持它,所以 angular 也不支持(嘘!)。您可能不得不满足于这样的事情:
template: '<input ng-show="model" ng-model="model" type="checkbox"/>' +
'<input ng-show="!model" ng-model="model" type="text"/>';
参考:change type of input field with jQuery
当具有变量输入类型复选框时,值设置不正确。
简化此代码以解决问题。
controller.coffee
angular.module 'tinyhandsAmenApp'
.controller 'TestrouteCtrl', ($scope) ->
@user =
admin: true
directive.coffee
angular.module 'tinyhandsAmenApp'
.directive 'formInput', ->
restrict: 'EA'
scope:
model: '='
template: '<input ng-model="model" type="{{ type }}"/>'
link: (scope, element, attrs) ->
scope.type = "checkbox"
example.html
<div class="col-md-12" ng-controller="TestrouteCtrl as tr">
<input type="checkbox" ng-model="tr.user.admin" />
<form-input model="tr.user.admin"></form-input>
</div>
结果 html 有 value="true"
这使得 Angluar 似乎将其视为文本框。如果我用 checkbox
替换 {{ type }}
那么它就可以了。指令中的输入和输出都设置正确。
我还发现如果我将指令 html 更改为
<form-input model="tr.user.admin" type="checkbox"></form-input>
指令js中的作用域对象为
scope:
model: '='
type: '@'
并从 link 函数中删除 scope.type = "checkbox"
它起作用了!
所以看起来 Angluar 在调用 link 之前使用 ng-model 设置输入元素的值。这有意义吗?
我想这个解决方案现在已经足够好了,但我真的很想能够从 js 中指定输入类型。
顺便说一下,如果类型是文本,我原来的方式就可以正常工作。
更新: 这里有一个 JSFiddle 说明了我在说什么。 form-input
不起作用。 form-input2
确实如此,但在 html.
UPDATE2: 我想做的是在 javascript 中指定输入类型并绑定到控制器。
您正在尝试做的事情无法完成。关于原因的简短回答是:Internet Explorer 不支持它,所以 angular 也不支持(嘘!)。您可能不得不满足于这样的事情:
template: '<input ng-show="model" ng-model="model" type="checkbox"/>' +
'<input ng-show="!model" ng-model="model" type="text"/>';
参考:change type of input field with jQuery