Why isn't the input reflecting changes in the model when I make updates?

http://jsfiddle.net/waGEU/1/

Attempting to dynamically add or remove elements from a list upon clicking, however encountering issues with removing the correct elements while adding them initially seems to function correctly.

The JavaScript code snippet:

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.tags = ['a', 'b', 'c']
        $scope.book = {tags: []}
        $scope.toggle_tag = function(tag) {
            index = $scope.book.tags.indexOf(tag)
            if (index == -1)
                $scope.book.tags.push(tag)
            else
                $scope.book.tags.splice(tag, 1)
        }
    });

The corresponding HTML code snippet:

<div ng-app="app" ng-controller="MainCtrl">
    <input type="text" ng-model="book.tags" ng-list="/ /" />
    <p>{{book.tags}}</p>
    <span class="tag" ng-repeat="tag in tags" ng-click="toggle_tag(tag)">{{tag}}</span>
</div>

Tags can be clicked on to either add or remove them. The ng-model is added to the input field, but upon clicking, the input does not update correspondingly. Looking for a solution to make it update properly.

Answer №1

Make sure to update the input by setting or binding its value property.

Revise this line

<input type="text" ng-model="book.tags" ng-list="/ /" />

to something similar like this

<input type="text" value="{{book.tags.join(',')}}" />

Also refer to shaunhusain's response for addressing the splice bug in your code.

See the updated demo with both corrections: http://jsfiddle.net/waGEU/6/

Answer №2

Make sure to provide the index, not the element, when using Splice function

http://jsfiddle.net/waGEU/2/

JavaScript

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.tags = ['a', 'b', 'c']
        $scope.book = {tags: []}
        $scope.toggle_tag = function(tag) {
            index = $scope.book.tags.indexOf(tag)
            if (index == -1)
                $scope.book.tags.push(tag)
            else
                $scope.book.tags.splice(index, 1)
        }
    });

Modified

                $scope.book.tags.splice(tag, 1)

to

                $scope.book.tags.splice(index, 1)

For the issue of binding not updating the input field:

http://jsfiddle.net/waGEU/5/

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.tags = ['a', 'b', 'c'];
        $scope.book = {tags: [], displayTag:""};
        $scope.toggle_tag = function(tag) {
            index = $scope.book.tags.indexOf(tag)
            if (index == -1)
                $scope.book.tags.push(tag)
            else
                $scope.book.tags.splice(tag, 1)
            $scope.book.displayTag = $scope.book.tags.slice(0);
        }
    });

Then connect the input to books.displayTag

The above code "works" but can be optimized by using:

<input type="text" value="{{book.tags.join(',')}}" />

for better performance in updating the binding.

Answer №3

If you need a solution for two-way binding, consider adding an additional variable.

<input type="text" ng-model="book.tagInputValue" />

Ensure synchronization with the book.tags array by using $scope.$watch

$scope.$watch('book.tags',
    function(newValue, oldValue, scope) {
        scope.book.tagInputValue = newValue.join(' ');
    },
    true
);

$scope.$watch('book.tagInputValue',
    function(newValue, oldValue, scope) {
        scope.book.tags = (newValue && newValue.length > 0) ?
            newValue.split(/\s+/) : [];
    }
);

Check out the updated jsFiddle: http://jsfiddle.net/waGEU/9/

You can consolidate all of this into your own directive if you anticipate having multiple books with similar input requirements. See: http://docs.angularjs.org/guide/directive#writingdirectivesshortversion

Note that updating an input field value in this manner may occasionally shift the cursor position, such as when deleting a tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing my directive to throw the $unknown provider error?

encountering an unknown provider error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr? p0=postbuttonsProvider%20%3C-%20postbuttons%20%3C-%20RandomBusinessCtrl take a look at my code : the directive is defined as below : angular.mod ...

Transferring text data to MVC Controller using AJAX

I am currently working on an AJAX feature that sends data to an MVC Controller method for a booking system app. I am trying to verify user input against an Entity Model. Although the parameters are being passed to the controller method through Ajax, I am n ...

How can one effectively incorporate a petite Angular.js application within a WordPress platform?

I'm currently in the process of integrating a compact AngularJS application onto my friend's Wordpress site. This app will gather user input and display output based on that data, while also recording the input for analysis purposes. In order to ...

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

Arranging an array according to the keys of the object

Here is a code structure with various participants: var person1 = { name : "", nickname : "", number "99999" } ; var person2 = { name : "bbb", nickname : "", } ; var person3 = { name : "", nickname : "aaa" } ; var person4 = ...

What is the most efficient way to send multiple uploaded files using AJAX instead of submitting them individually?

Below is the code for submitting a file on drop and calling ajax at the same time. However, I attempted to modify it so that users can drop multiple files and submit them all at once. I wrapped the function that sends the file to ajax with an onClick even ...

A common error message that occurs in programming is "Error: (intermediate value)

I'm experiencing an issue with a cookie popup that I'm trying to interact with or disable in order to ensure the accuracy of my Axe accessibility tests. What would be the most effective approach in this scenario? Currently, I am attempting to cli ...

I'm currently leveraging Vue.js and Python Flask for my backend development. I'm looking to establish some local variables. What is the best way to accomplish this?

Here is my Vue js file where I am utilizing two URLs from localhost. My goal is to create a configuration file that will allow me to make changes in one place and have those changes reflected throughout. <template> <div> <div class="glob ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Tips for dynamically inserting a tabbed element into a list using AngularJS

I am trying to dynamically add elements with tabs in the list, but I encounter a problem where the device info gets overridden from the last user. You can see the issue here: https://i.sstatic.net/O1uXK.jpg This is how my Tabs item looks like in HTML: & ...

The Ajax request fails to send the form files

I'm encountering an issue where a form isn't passing one variable. Here is my table structure: Schema::create('projects', function(Blueprint $table) { $table->increments('id'); $table->string(&apos ...

Discovering the culprit code responsible for involuntary routing in a legacy website

I am seeking assistance with troubleshooting a problem I am facing while working on revamping an old AngularJS based website. I keep coming across unexpected routing events triggered by unknown code. When clicking on various elements on the site which do ...

When using VSCode for Next.js projects, automatic imports from "react" are not supported

* While similar, this question is not a duplicate of this other question; the solutions provided there are tailored for TypeScript and do not seem to apply to JavaScript. In my current project using Next.js in Visual Studio Code, I am facing an issue wher ...

What could be causing the malfunction of my two-way data binding in Ionic?

While working on a project in Ionic, I ran into issues with my data-binding. I'm struggling to understand why this is happening. To troubleshoot, I created a new Ionic project using "ionic start myApp sidemenu" to test the data binding. Even in the n ...

Validating input when it is blurred

I am facing an issue where I want field validation to trigger only when the user leaves the field. Despite trying various techniques like those mentioned in this Stack Overflow thread about jQuery validation onblur (specifically francios wahl's respon ...

Counting items in AngularJS filters: a step-by-step guide

I have a question regarding my jsfiddle example. Here is the link to my jsfiddle How can I ensure that it counts the number and only displays once instead of repeating multiple times? This is my HTML code: <section class="left" style="border-right:1 ...

Change the `display: none` of elements back to their original value

Explanation In my coding practice, I have implemented a script that hides certain elements if the user lacks the necessary permission to interact with them. To achieve this, I utilize the CSS property display: none. However, when it comes time to reveal ...

How can I send back multiple error messages from a pug template in a node.js application with Express?

I am currently working on validating inputs from a form on a Node.js web server using Pug.js and Express.js. The issue I am facing is that when there are multiple problems with the user's input, only the first error is displayed to the user. How can I ...

Switch up the header's date format on NGX-Print

Within my application, I am utilizing ngx-print with Angular 8. When I click the print button, a date in the format mm/dd/yy is added to the header. However, I would like to change it to dd/mm/yy. Despite searching, I have been unable to find any document ...

The cookie was not successfully initialized

Working with asp.net xss scripting, I encountered a situation where one page sent a post request and received a cookie in the response. However, even though the header indicated that the cookie was returned, the browser failed to set it, resulting in docum ...