Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown?

I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to the multipleDemo array and disappear from the select dropdown. Unfortunately, once selected, these names cannot be chosen again from the dropdown. To solve this issue, I need a Delete button functionality to remove all elements (except the first one) from the multipleDemo array and place them back into the people array. This way, users can once again select any name from the dropdown. There seems to be an error in the function $clearTag.

Expected behavior:

  1. Select: Wladimir
  2. Wladimir tag appears
  3. Try to select Wladimir again (this should not be possible as Wladimir is already selected)
  4. Click on Delete. The tags stored in the multipleDemo array should be removed and placed back in the people array.
  5. You can now select Wladimir or any other name again.

Link to code snippet for reference: http://plnkr.co/edit/TPZjXkkSRrIc5ApzP07F?p=preview

index.html

<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
  <meta charset="utf-8">
  <title>AngularJS ui-select</title>;

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-sanitize.js"></script>
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css">;

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

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

  <!-- Select2 theme -->
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.css">;
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.default.css">;

  <style>
    body {
      padding: 15px;
    }

    .select2 > .select2-choice.ui-select-match {
      /* Bootstrap inclusion */
      height: 29px;
    }

    .selectize-control > .selectize-dropdown {
      top: 36px;
    }
  </style>
</head>
<body ng-controller="DemoCtrl">
    
  <h3>Array of strings</h3>
  <button ng-click='clearTag()'>Delete</button>;
  <ui-select tagging tagging-label="new tag" multiple ng-model="multipleDemo" 
  on-select="OnClickSelect($item)" on-remove="OnRemoveSelect($item)"
  theme="select2" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select name...">{{$item.name}}</ui-select-match>
    <ui-select-choices repeat="item in people | filter:$select.search">
      {{item.name}}
    </ui-select-choices>
  </ui-select>
  <p>Selected: {{multipleDemo}}</p>;
  <hr>;;

</body>;
</html>;

demo.js

app.controller('DemoCtrl', function($scope, $http, $timeout) {
  $scope.multipleDemo =[];
    $scope.people = [
    { name: 'Adam', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f594919498b59098949c99db969a98"', age...
  
  $scope.OnClickSelect=function(item)
  {
   $scope.multipleDemo.push(item.name);
  };
  
  $scope.OnRemoveSelect = function(item) { 
   var index = $scope.people.indexOf(item.name);
   $scope.people.splice(index, 1); 
  };
  
  $scope.clearTag = function() {
    for(var i =0; i < $scope.multipleDemo.length; i++) {
      $scope.multipleDemo.splice($scope.multipleDemo[i], 1000);
      $scope.people.push($scope.multipleDemo[i]);
    }
  };;
})

Answer №1

Resolving Common Issues with Angular-UI-Select

ng-model Issue: Using a Simple Variable on $scope

If you are facing issues with the ng-model directive and a simple variable on $scope, make sure to follow this correct syntax:

CORRECT

<ui-select ng-model="vm.multipleDemo"> <!-- Correct -->
  [...]
</ui-select>

Ensure that your controller initializes the vm object for it to work correctly:

app.controller('DemoCtrl', function($scope, $http, $timeout) {
    $scope.vm = { multipleDemo: [] };

To learn more about resolving common issues with AngularUI-Select, visit the AngularUI-Select FAQ page.


Update: Addressing Scope Hierarchy Concerns

If vm.multipleDemo is not working and you resort to using $parent.multipleDemo, understanding scope inheritance is key. Make sure to initialize the vm object in the controller:

app.controller('DemoCtrl', function($scope, $http, $timeout) {
    $scope.vm = { multipleDemo: [] };

Issues with primitives can be avoided by adopting best practices such as incorporating a '.' in your ng-models. This resolves problems related to data hiding when directives like ng-repeat and ng-switch create child scopes.

Utilizing $parent to fix data hiding concerns is deemed a code smell, indicating a deeper problem in the application structure.


Update #2: Understanding Controller Instantiation

When should I use $ctrl in the view and this in the controller?

If the controller is instantiated using "controller as" syntax:

<body ng-controller="DemoCtrl as $ctrl">

    <ui-select ng-model="$ctrl.multipleDemo">
       <!-- -->
    </ui-select>

In this scenario, bypass using $scope altogether:

app.controller('DemoCtrl', function($http) {
    this.multipleDemo = [];

This approach eliminates data hiding complications.

To delve further into the 'this' vs. $scope debate in AngularJS controllers, refer to this 'this' vs $scope discussion.

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 the correct method for setting a scope variable from a service in Angular?

Is there a way to retrieve the return value from a service method and set it into the scope for further processing in the template? I've discovered that I cannot directly access the scope within services. While I could use Rootscope, I believe there ...

Is there a way to verify if debugging information is enabled within an Angular application?

If you want to switch angular's debug information on or off, you can achieve this by using the following code: $compileProvider.debugInfoEnabled(debugInfoState); This should be included within the config method of your Angular application. Is there ...

Using CSS to position elements absolutely while also adjusting the width of the div

In one section of my website, I have a specific div structure. This structure consists of two divs stacked on top of each other. The first div is divided into two parts: one part with a width of 63% and another part with a button. Beneath the first div, t ...

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

Choose the camera when utilizing the navigate.getUserMedia() function

I am currently utilizing the navigate.getUserMedia() method to record video on my mobile device and perform additional processing on it. However, at the moment, it is only capturing video using the front camera. How can I make it switch to the rear facing ...

Identifying duplicate values in an array of objects using JavaScript

I am facing an issue with my array that collects data from a spreadsheet into studentCCAList. Sometimes, a student may have multiple subjects. For example, Name: Joseph Subject: English Name: Peter Math Name: Joseph Subject: Science My concern i ...

angularjs - the datepicker popup is displayed for both the start date and end date

Is there a way to prevent the datepicker popup from appearing when clicking on just one input field? Plunkr <form> <div class="form-group"> <label for="fromDate">From:</label> <input type="text" clas ...

Tracking the progress of reading position using Jquery within an article

Here is an example of a reading progress indicator where the width increases as you scroll down the page: http://jsfiddle.net/SnJXQ/61/ We want the progress bar width to start increasing when the article content div reaches the end of the article c ...

AngularJS attempting to conceal the popup menu upon clicking outside of the designated area

My HTML structure looks like this: <div> <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a> <div class="options_box" ng-show="$scope.show_menu"> <button>Option1</button> ... ...

Utilizing Vue.js to initiate a server request with vue-resource

Seeking guidance on performing a server call using vue-resource. I'm unsure about how to set the header and send data via Vue.$http.post Vue.$http.post('http://url/', { email: 'foo', password: 'bar' }, { headers: { ...

difficulty arises when attempting to invoke a viewmodel from another viewmodel inside a ko.computed function

Is it possible to have two view model functions in my JavaScript where one references the other? I am encountering an error with this setup. Here are my view models: var userViewModel = function (data) { var _self = this; _self.ID = ko.obs ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Excel sheet upload button in Angular not functioning as expected

My project utilizes the Angular file upload component, which can be found at https://github.com/danialfarid/angular-file-upload Previously, everything was functioning correctly. However, after some refactoring, I seem to have inadvertently caused a breaka ...

Looking for assistance in setting up a personalized slideshow to automatically play on its

Recently, I have taken responsibility for a project that was initiated by someone else. The website contains a customized slideshow on its homepage. To meet the client's requirements, I have already made some alterations to the appearance and feel of ...

What is a way to nest a promise request within another request?

Q: How can I create a new promise within a request, and then return it in a nested request? Here is the code snippet: request({ // --------------request 1------------ url: request_data.url, method: request_data.method, form: request_data.data ...

The division element nested within a select tag

HTML: <div class="row"> <div class="form-group"> <div class="col-xs-10"> <label for="class_code_reservation">Class Code</label> <select type="text" class="form-control" id="class_code_reservation" na ...

What steps do I need to take to set up CORS properly in order to prevent errors with

I encountered the following error message: "Access to XMLHttpRequest at 'api-domain' from origin 'website-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HT ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

Any ideas on how to fix the error that pops up during the installation of the bootstrap package in Node

The npm command is not recognized as a valid cmdlet, function, script file, or operable program. Please double check the spelling of the command and ensure that the path is correct before trying again. This error occurred at line 1. npm i bootstrap + ...