MrM
MrM

Reputation: 21989

How do I set input type based on variable in angularjs?

How do I set up an input type based on another variable? (My initial thought was to have) the directive trigger from the onclick event, which should set the input type. I thought about using a directive but not sure

FIRST

//loop
<a class="orgTitle" id="@c.Id" data-ng-click="selectQuestion(@c.Id, @c.SelectionTypeId);" style="cursor:pointer">@c.ProgramName</a>

THEN

$scope.selectQuestion = function(id, selectionTypeId) {//call returns data and push to QuestionList}

FINALLY

<div data-ng-repeat="question in angularPage.QuestionList">
<span>{{question.Question}}</span><br/>
<span>//directive to get my answer type, whether radiobutton or textbox</span>

Upvotes: 1

Views: 1738

Answers (2)

MrM
MrM

Reputation: 21989

I... I mean, we figured it out! Because jquery restricts the type property change, I did an append on the html input type.

HTML

<input-type question-type="question.myDynamicInputType" />

js

.directive('inputType', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attr) {
            $(element).append('<input type="' + scope.$eval(attr.inputType) + '" />');
        }
    }
});

element

<input-type question-type="question.myDynamicInputType">
    <input type="number">
</input-type>

Thanks for your help guys!

Upvotes: 0

angabriel
angabriel

Reputation: 5028

Try writing a directive like this: Pseudo-Code, this was not tested!

angular.module('inputType', [])
  .directive('inputType', function (/**injects here*/) {
    return {
      restrict: 'A',
      scope: false,
      link: function (scope, element, attr) {
        var inputType = scope.$eval(attr.inputType);
        element.attr('type', inputType);
      }
  })
});

Then in html:

<input input-type="myDynamicInputType" />

Upvotes: 2

Related Questions