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

Combine and total various multidimensional associative arrays

I'm looking for a solution to merge multiple arrays, each containing nested keys and values, and summing any duplicate keys or sub-keys that may exist. For instance: $arr1 = [ "Friday" => ["Breakfast" => 32, "Lunch& ...

Translating Python's slicing assignment syntax to JavaScript/TypeScript: A guide

Currently, I am in the process of converting a Python library into TypeScript. One specific challenge I am facing is translating this line of code from this particular repository: is_prime[start - segment_min::pk] = repeat(False, len(range(start - segment ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

Locating the value of a data attribute from a distant parent div using jQuery

How can I access the closest div from an anchor tag that has a data-id attribute without using multiple parent() methods? Even though .parent().parent().parent() works, I am trying to find a better solution. <div class="panel panel-default" data-id="@ ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

Issues persist with debugger functionality in browser development tools following an upgrade from Angular 8 to version 15

After upgrading from Angular version 8 to version 15, I've encountered an issue where the debugger is not functioning in any browser's developer tools. Can anyone provide some insight on what could be causing this problem? Is it related to the so ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

Can you explain the purpose of the .subscribe() function?

Currently, I am in the process of developing an API using Angular2 and NodeJS. My focus has been on implementing services for my API that are responsible for retrieving a list of tasks and presenting them. Below is the code snippet for the task service: i ...

Issue: Catching errors in proxy function calls

I am currently using Vue 3 along with the latest Quasar Framework. To simplify my API calls, I created an Api class as a wrapper for Axios with various methods such as get, post, etc. Now, I need to intercept these method calls. In order to achieve this ...

Only display the element if there is corresponding data available

I have implemented the angular ng-hide directive to conceal certain markup when there is no data present: <li class="header" ng-hide = " todayRecents.length === 0 ">today</li> At this point, ng-hide simply applies a display value of 'non ...

Transforming Nested JavaScript Objects for Internationalization in Vue

In my VUE JS web application that utilizes i18n-vue, I am facing an issue with reformatting a JS Object to work with the i18n-vue setup. The translations are retrieved from the database and are structured in a certain way as shown below. I have tried seve ...

Replace async/await with Promise

I want to convert the async/await code snippet below: const mongoose = require('mongoose') const supertest = require('supertest') const app = require('../app') const api = supertest(app) test("total number of blogs" ...

Confusion arises when applying Angular filter to the numbers 1000, 100, and

I'm currently managing a database where a particular field can have values of 10, 100, or 1000. When filtering to display only the records with a value of "10," it also displays records with values of "100" and "1000." Is there an easy solution for th ...

A guide on transferring and transforming text data on the server

While I have a basic understanding of php, ajax, and javascript (including jQuery), I am still a beginner and could use some assistance with connecting the dots for this simple task: My goal is to allow the user to input text (for example: "I saw the sun, ...

Is it possible to return to the previous page in Vue by using window.history.go(-1)?

Greetings! I am currently developing a website using Vue, but I have encountered an issue. Initially, I tried using router.go(-1) to prevent access through the address bar (e.g., from ../client/mypage to ../admin/mypage) and to redirect to the previous pag ...

Modify route title and component if user is authenticated

I've successfully implemented a login feature in my Nativescript-Vue application that utilizes the RadSideDrawer component. My current challenge is to change the route from 'Login' to 'Logout', and I'm struggling to find a wa ...

What is the best way to target the specific DIV using a jQuery selector?

My dynamic div is filled with other divs... <div id="wrapper"> </div> //javascript for(//lots of times){ var d = document.cloneNode('divModel'); d.foo = {//a lot of stuff }; document.getChildById('wrapper').append ...

What are the steps to store a firebase storage downloadURL in a firestore collection?

I'm facing an issue with saving my firebase storage image into a firestore collection variable. Initially, it was working correctly but suddenly stopped functioning, and now the image variable is returning null. Note: I am using the asia-south1 serve ...

Strategies for filtering fields in LoopBack based on the included model

Here is my query that I am working on: UserModel.find({ filter: { include: [ "communications", "roles" ], where : { "object_type" : 1 } } }, function(data){ $root ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...