The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure:

$scope.people = [
{ name: 'Niraj'},
{ name: 'Shivam'},
{ name: 'Arun'},
{ name: 'Mohit'}]

There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names from the array and ensure that the default selection in Angular UIselect matches the array value.

https://i.stack.imgur.com/s8Gox.jpg

Refer to the figure provided. I also want to ensure that only newly added values are displayed upon clicking the "click me" button (Desired outcome). If all values are shown, it should not be an issue.

Check out my plnkr.

Answer №1

After much searching, I have finally discovered the solution for filtering and listing values based on conditions in my demo.js file.

'use strict';

var app = angular.module('demo', ['ngSanitize', 'ui.select']);

app.controller('DemoCtrl', function ($scope, $http, $timeout, $interval) {

  $scope.oldArray = [];
  $scope.people = [
    { name: 'Niraj'},
    { name: 'Shivam'},
    { name: 'Arun'},
    { name: 'Mohit'},
    { name: 'Koushik'},
    { name: 'KedaBro'},
    { name: 'Tripathi'},
    { name: 'Nlma'}, 
    { name: 'Nshma'},
    { name: 'BsCoder'}
  ];
  var people = $scope.people;
  var oldArray = [];

  var array = "Niraj,Shivam";
  array = array.split(",");
  for(var i=0 ; i < array.length ; i++){
    oldArray.push({
      name : array[i]
    });
  }
  
  var filteredArray = people.filter(function(itm){
    return array.indexOf(itm.name) < 0;
  });
  $scope.filteredArray = filteredArray;
  console.log(filteredArray); 

  $scope.multipleDemo = {};
  $scope.multipleDemo.selectedPeople = [];
  for(var  i = 0 ; i < array.length ; i++){
    $scope.multipleDemo.selectedPeople.push({name : array[i]});
  }

  $scope.submitValue = function(){
    console.log($scope.multipleDemo.selectedPeople);
  }
});

This is my html file

<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
    <meta charset="utf-8">
    <title>AngularJS ui-select</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-sanitize.js"></script>

    <!-- ui-select files -->
    <script src="./select.js"></script>
    <link rel="stylesheet" href="./select.css">

    <script src="./demo.js"></script>

    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css">    
</head>
<body class="ng-cloak" ng-controller="DemoCtrl as ctrl">
  <h1>Multiple Selection</h1>
  <ui-select multiple ng-model="multipleDemo.selectedPeople" theme="bootstrap" ng-disabled="ctrl.disabled" sortable="true" close-on-select="false" style="width: 500px;">
    <ui-select-match placeholder="Select person...">{{$item.name}}</ui-select-match>
      <ui-select-choices repeat="person in filteredArray">
        <div ng-bind-html="person.name"></div>
      </ui-select-choices>
  </ui-select>
  <button name="button" ng-click="submitValue()">Click me</button>
</body>
</html>

Link to Plnkr

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

Guidance on handling JSON data containing both nested and non-nested structures

Within file 1, the JSON element "image" is nested in a structured format: {"id": "0001", "type": "donut", "name": "Cake", "image":{"url": "images/0001.jpg", "width": 200, "height": 200}} Spark successfully infers the schema from the data: val df1 = spar ...

JavaScript Click Event Not Functioning

I am attempting to create an interactive feature where clicking on any image will either reveal a clear version of the picture if it is blurred, or blur the picture if it is clear. The current issue I am facing is that when I click on a blurred image, it ...

Issue encountered while importing TypeScript files from an external module in a Next.js project

Encountering an issue within my Next.js project with the following project structure: ├── modules/ │ └── auth/ │ ├── index.ts │ ├── page.tsx │ └── package.json └── nextjs-project/ ├─ ...

How can I configure the dataSource using a JSON data feed in FuelUX Tree component?

I'm currently working on setting up a json data source for the FuelUX tree. To achieve this, I have created a PHP file that echoes a JSON encoded array which results in something like: [{"name":"South Africa","type":"folder","additionalParameters":{" ...

By default, the D3 hierarchy will collapse to the first level

I've been working on code to create an indented tree structure. My goal is to initially collapse the tree and show only the first level children or the root node. I tried a few different approaches, but none were successful. The current portion I have ...

Creating Seamless, Unified Shape-to-Shape (Containers) Transition with CSS and JavaScript - A Step-by-Step Guide

I am experimenting with creating a unique effect where two rectangular shapes, each containing text and with rounded ends, move towards each other, merge to form a single rounded rectangle as the page is scrolled down, and then separate back when scrolling ...

creating a post action using Node.js with Express and Angular

Process Overview I have an Angular post that communicates with my Node.js Express backend to send data to an API. My goal is to redirect the user to a different Angular page upon successful post, or display an error message if the post fails. One approac ...

Trigger function in React after the page finishes loading

I have a scenario where I need to display images onDrop within one of my components. To ensure a smooth drop experience, I am considering preloading the images using the following approach: componentDidMount(){ this.props.photos.forEach(picture => ...

res.json is providing HTML output instead of JSON

Initially, everything was working smoothly. However, now I am encountering an issue where errors that should be in json format are being returned as html instead. For example, when there is an error such as an invalid password, the response I receive is in ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Transforming a JavaScript array into a JSON format

Is there a way to convert a JavaScript array into JSON format? [{ "userName": "Rodrigo", "date": "April 25, 2017", "score": 5 }] [{ "userName": "Jon", "date": "April 24, 2016", "score": 4 }] Error: There is a parser error on line ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

Modify text using JQuery when the span is clicked

Currently, I am attempting to retrieve a value from the database: SenderDriver->total_trips. Everything seems fine, but I have a specific id that needs to be placed within onClick(), which then sets the value of the database variable: SenderDriver-> ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...

Guide on attaching an onclick event to a button created with a string in Next.js?

<div onClick={(event) => this.addToCart(event)}> <ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml /> </div> In my current situation, I am facing an issue with the code above. The button is being rendered ...

Struggling to make ng-repeat function properly within an AngularJS controller when working with arrays

I am having trouble with my code. The ng-repeat in my AngularJS app is displaying blank. Can someone help me figure out why? Thanks in advance, Stephanie <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/aja ...

Error: Unable to execute setState in React Native

Why am I receiving an error stating that this.setState is not a function? I'm having trouble understanding why my code isn't working as expected. import React from 'react'; import axios from 'axios' import { StyleSheet, Text ...