How can you assign various models to a single directive?

Exploring angularjs, I am interested in creating a dual list box with two lists - one on the left containing all items, and another on the right for selected items that can be transferred back and forth. Using arrows to facilitate this movement.

While it is achievable using plain HTML and angularjs, I am intrigued by the idea of making it reusable through something like:

<dual-list-box all-items='currentController.allItems' selected-items='currentController.selectedItems' />

This way, I could pass in different lists regardless of the controller or list names, ensuring versatility for my dual list box control.

Is there a way to make this possible? Any thoughts on how to approach this? I believe a directive might be the solution, but I am uncertain about the implementation.

Perhaps my approach needs some refining...

Answer №1

To make this work, you can create a directive like the following example:

module.directive('dualListBox', function() {
    return {
        restrict: 'E',
        scope: { // isolated scope to bind parent scope properties
            allItems: '=',
            selectedItems: '='
        },
        template: 'HTML template that binds to allItems and selectedItems in isolated scope',
        link: (scope, elm, attr) {
            // use scope.allItems & scope.selectedItems here
        }
    }
});

Make sure to consult the directive documentation while implementing.

Answer №2

Check out this demonstration, which maintains the method for transitioning between the two elements within the directives scope. Instead of utilizing arrows (as it was unclear if you meant moving only the bottom element, having an arrow for each element, or something else), you simply have to click on an element to shift it over.

myApp.directive('duallist', function() {
return {
    restrict: 'E',
    replace: true,
    scope: {
        data1: '=',
        data2: '='          
    },
    template: '<div><ul class="list"><li ng-repeat="datum in data1" ng-click="move(datum, data1)">{{datum}}</li></ul> <ul class="list"><li ng-repeat="datum in data2" ng-click="move(datum, data2)">{{datum}}</li></ul></div>',
    link: function(scope, ele, attrs) {
        scope.move = function(datum, dataset) {
            if (dataset == scope.data1) {
            scope.data2.push(datum);
            dataset.splice(dataset.indexOf(datum), 1);                  
            }
            else{
            scope.data1.push(datum);
            dataset.splice(dataset.indexOf(datum), 1);    
            }     
        }
    }
}

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

How to manipulate local JSON files using AngularJS

I recently started learning angularjs and have been spending hours online trying to figure out how to access data from a local json file without the need for hosting it on localhost. Unfortunately, I haven't come across any solutions yet. I attempted ...

Embedding $sce functionality within a controller

I am facing a challenge where I have HTML content coming in as a string and I need to render it. After exploring options, I am considering using ng-bind-html, which requires $sce to be injected into the controller. Most of the examples I found online show ...

Showing Information Using Angular

I am working on a form that includes a dropdown element. The options in the dropdown are actually IDs from a different table. After clicking save or add, the data is sent to the server and then displayed in a dynamic table below the form. However, I am fa ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Data not populating correctly in MEAN Stack application

Currently grappling with the challenge of making this web app operational using the MEAN Stack, I find myself at a standstill. The root cause is unclear to me. Upon refreshing my page and commencing data entry by filling out all fields before clicking on " ...

Page not found: The requested file does not exist

Apache web server is claiming that the page we are attempting to reach is missing, even though we are certain it is not. It gets even more puzzling as only directory names seem to be causing issues. It's not a file permissions problem be ...

Ionic retrieves a filtered array of JSON data

Having difficulty filtering the array to retrieve values where the parent id matches the id that is provided. For instance, if an ID of 1 is sent, it should result in a new array with 3 items. An ID of 4 will return 1 item, and an ID of 5 will also return ...

Invalid Credentials - ajax authentication - Symfony2 / AngularJS / FosUserBundle

I have successfully implemented FosUserBundle with the regular web/app_dev.php/login login. The AuthenticationHandler is set up as shown here. When my Angular application sends a JSON request, it includes the following data: _csrf_token: "uSRZfxMycFCLKbx ...

What is the best way to change a variable in an AngularJS view?

My Request In my application, I have implemented 3 views, each with its own controller. The first view is the home screen, and from there the user can navigate to view 2 by clicking on a div element. On view 2, the user can then move to view 3 by clicking ...

Determining the cursor location within a character in a div that is content editable using AngularJS

I am facing challenges with obtaining the cursor caret position within a contenteditable div. Currently, I am utilizing the following function : onBlurArea (field, ev) { ev.preventDefault() const editable = ev.target.childNodes[1].childNodes[2] ...

How can I programmatically refresh a recursive ng-include in AngularJS?

Using a recursive script within my Angular application, I am displaying a visualization of multiple objects. However, whenever I modify the structure of an object dynamically, the view does not automatically update. It appears that the ng-include directiv ...

Array not being updated and reset with submitted form information

Within my controller, there exists a straightforward array and function: $scope.newGuarantor = ''; $scope.guarantors = [ {guarantor: 'Peter Parker'}, {guarantor: 'Bruce Wayne'} ]; $scope.addGuarantor = function(){ ...

What is the best way to append an element to the end of an array in Angular JS?

One of the arrays that I am working with in Angular JS is called $scope.messages = []; In my template, I use ng-repeat: <div ng-repeat="item in messages"></div> When attempting to add a new element to the end of the array, I follow these ste ...

Conducting an AngularJS AJAX call within a Symfony2 environment and utilizing Doctrine to generate a JSON

Currently, I am working on a project involving Symfony2, Doctrine, and AngularJS. While Symfony2 and Doctrine are not causing any issues, I am facing difficulties when using an ajax request with AngularJS. The problem lies in either the data not loading pr ...

Tips on transforming JSON data into a hierarchical/tree structure with javascript/angularJS

[ {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"1","zid":"1","statename":"Karnataka"}, {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"2","zid":"1","s ...

What are effective strategies for safeguarding my AngularJS application code, particularly from unauthorized access through the browser's source code?

I am currently working on an AngularJS application. I have encountered a challenge where the end user is able to view the app code from the browser's source code. I am seeking advice on how to address this issue effectively. Is there any recommended ...

obtain direct access to the $scope variable when using ng-if

Is there a more effective way to access scope created by ng-if in my directive without using $parent.params.text? <span ng-if="params" uib-tooltip="{{params.text}}"></span> .directive('myDirective', functions(){ return { te ...

"Step-by-step guide on populating a select box with data from the scope

Hey everyone, I'm new to using Angular and hoping for some help with a simple question. I've created a form (simplified version below) that I want users to see a live preview as they fill it out. Everything was going smoothly with regular field ...

Deactivate an option within an angularjs multi-select menu

Currently, I am utilizing an angularjs multiselect box which is displayed below: https://i.stack.imgur.com/w6ffN.png Here is the html code snippet: <select multiple ng-options="Language.LangID as Language.LangName for Language in AllLanguages " ng-mo ...

What is the purpose of ng-submit blocking the default action?

According to the ng-book: The ng-submit directive is used to connect an expression to an onsubmit event. It also stops the default action (sending the request and refreshing the page), unless the form includes an action attribute. Can you explain the sig ...