简体   繁体   中英

Issue with angular, ng-model, and inputs

EDIT: Jonathan's suggestion worked. I tried using version 1.1.5 and that throws a "Duplicates in a repeater are not allowed" error for the duplicate empty strings. I'll accept an answer when I get home from work, this browser does not have much enabled.

I am having an issue with using ng-model in an input tag. I have set up a JSFiddle which contains my code. The issue occurs when you click "Add" and then try to change one of the input boxes below. The input refuses to let you type in it!

HTML:

<div ng-class="{selected: selectedPart==$index, cell: selectedPart!=$index}" 
     ng-click="selectPart($index)" ng-repeat="part in parts">
        <textarea class="prompt" ng-model='part.wording'></textarea>
        <hr>
        <span class="numbering" ng-repeat="option in part.options">
            {{ $index+1 }}).
            <textarea class="option" ng-model="option"></textarea>
            <br>
        </span>
</div>

JS:

StaticEX.controller('mainController', function($scope) {
    $scope.parts = [];
    $scope.ps = "Problem Statement";
    $scope.selectedPart = null;


    $scope.newPart = function() {
        return {"wording": "Prompt",
                "options": ["", "", "", ""]}
    };

    $scope.addPart = function() {
        $scope.parts.push($scope.newPart());
    };

Is this an issue with how I am referring to "option"? Is this a pseudo-variable that is created for the "ng-repeat" directive and isn't actually linked to "$scope"? Or am I doing something profoundly stupid?

As far as dealing with the Duplicates in a repeater are not allowed with 1.1.5, there is a simple fix. I had this same issue when switching to 1.1.5 a few weeks ago.

track by $ index is needed as part of the expression of ng-repeat

<span class="numbering" ng-repeat="option in part.options track by $index">
   {{ $index+1 }}).
   <textarea class="option" ng-model="option"></textarea>
   <br>
</span>

You can read a little bit about this issue at this blog , on GitHub , or Angular Google Group .

Sometimes angular has trouble binding to non-objects. So the quick solution is to make your options objects.:

$scope.newPart = function() {
    return {"wording": "Prompt",
            "options": [{text:""}, {text:""}, {text:""}, {text:""}]}
};

and then

<input class="option" ng-model="option.text">

I thought this particular issue was resolved in later versions though, so try it with the latest version of angular and if it still doesn't work I'd file an issue for it on github.

If you change

<input class="option" ng-model="option">

To

<input class="option" ng-model="part.options[$index]">

It seems to work, but now you have issues with focus changing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM