我试图在change事件上更新scope.answers值。但无法在链接功能中更改当前值。
指令
function textControlDir()
{
return {
transclude: true,
restrict: 'E',
require:'ngModel',
/*scope: {
queObj: '=',
selectedAns: '='
},*/
template: '<div class="form-group">\n\
<label for="{{queObj._attributeName}}" class="col-sm-5 control-label">{{queObj._text}}</label>\n\
<div class="col-sm-6"><input type="text" name="{{name}}" class="form-control" id="{{id}}" value="{{selectedAns}}"></div>\n\
</div>'
,
link: function (scope, element, attrs,ngModel)
{
var queObj = scope.que.QuestionData;
scope.queObj = scope.que.QuestionData;
scope.name = queObj._attributeName;
scope.id = queObj._attributeName;
var selectedAns = '';
if(scope.answers)
{
selectedAns = scope.answers[scope.name];
}
if(selectedAns && selectedAns != '')
{
scope.selectedAns = selectedAns;
}
else
{
scope.selectedAns = scope.queObj._pageAttributes.defaultValue;
}
element.bind('change',function(){
scope.answers[scope.name] = document.getElementById(scope.id).value;//element.value();
console.log(scope.answers[scope.name]);
scope.$apply();
})
}
};
}
HTML
<div ng-repeat="que in questions[$state.current.name]">
<div ng-if="que.QuestionData._fieldType === 'text'" >
<text-control-dir data-que-obj="que.QuestionData" data-ng-model="answers[que.QuestionData._attributeName]"></text-control-dir>
{{answers[que.QuestionData._attributeName]}}
</div>
<div ng-if="que.QuestionData._fieldType === 'select'" >
<select-control-dir data="que.QuestionData"></select-control-dir>
</div>
<div ng-if="que.QuestionData._fieldType === 'radio'" >
<radio-control-dir data="que.QuestionData"></radio-control-dir>
</div>
<div ng-if="que.QuestionData._fieldType === 'hidden' && que.QuestionData._attributeName != 'CBQ'" >
<hidden-control-dir data="que.QuestionData"></hidden-control-dir>
</div>
</div>
在$ scope.questions中有问题,我在index.html中循环。对于我正在创建输入的每个问题。如果$ scope.answers具有我在输入框中显示的特定输入的值。这很有用。现在,如果用户在输入框中更改任何内容,我希望在答案中设置值。
下面的代码不能使用指令(element.val;给出undefined)
element.bind('change',function(){
scope.answers[scope.name] = document.getElementById(scope.id).value;//element.value();
console.log(scope.answers[scope.name]);
scope.$apply();
})