0

My angular experience is basically about 3 days part time, so there's probably something simple I'm missing here.

I'm trying to create a dynamic list of multiple inputs based on an array, which I then want to reference from elsewhere in the app. What I've tried is loading a template from a custom directive, then $compile-ing it. <input data-ng-repeat="term in query" data-ng-model="term"> My controller contains $scope.query = [""] which successfully creates the first empty input box. But the input box doesn't seem to update $scope.query[0] when I modify it. This means that when I try to create another empty input box with $scope.query.push(""); (from a keypress listener looking for the "/" key) I get a "duplicates not allowed" error.

I've tried manually listening to the inputs and updating scope.$query based on their value, but that doesn't feel very "angular", and results in weird behaviour.

What do I need to do to link these values. Am I along the right lines or way off?

1
  • for the 'duplicates not allowed' error try data-ng-repeat="term in query track by $index" Commented Feb 12, 2015 at 23:45

1 Answer 1

2

I made a simple jsfiddle showing how to use an angular model (service) to store the data. Modifying the text inputs will also modify the model. In order to reference them somewhere else in your app, you can include TestModel in your other controllers.

http://jsfiddle.net/o63ubdnL/

html:

<body ng-app="TestApp">
    <div ng-controller="TestController">
        <div ng-repeat="item in queries track by $index">
            <input type="text" ng-model="queries[$index]" />
        </div>
        <br/><br/>
        <button ng-click="getVal()">Get Values</button>
    </div>
</body>

javascript:

var app = angular.module('TestApp',[]);

app.controller('TestController', function($scope, TestModel)
{
    $scope.queries = TestModel.get();

    $scope.getVal = function()
    {
        console.log(TestModel.get());
        alert(TestModel.get());
    }
});

app.service('TestModel', function()
{
    var queries = ['box1','box2','box3'];
    return {
        get: function()
        {
            return queries;
        }
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for your help. I managed to solve the problem, although I'm not actually sure what it was! Your example has helped me to better structure my code though, which not only solved this problem, but will prevent a number of headaches in future.
I've only recently started using models this way. It makes for a lot better structured code. Glad I could help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.