Create a bespoke AngularJS directive for a customized Twitter Bootstrap modal

I am attempting to create a unique custom Twitter Bootstrap modal popup by utilizing AngularJS directives. However, I'm encountering an issue in determining how to control the popup from any controller.

<!-- Uniquely modified Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Hello Custom Modal</h4>
  </div>
  <div class="modal-body">
    <p>Modified Modal PopUp</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  </div>
</div>

Additionally, here is my customized controller directive:

var customModal = angular.module('customDirectiveModal', ['ngRoute','ngAnimate']);
customModal.directive('loginCustomModal', function() {
  return {
    restrict: 'EA',
    templateUrl: 'directiveTemplate/modal.html',
    link: function(scope,elem,attr)
    {
        elem.bind("click",function()
        {
            console.log("Opening Custom Modal");
        });
    }
  }
});

Lastly, this is how I have invoked the directive from the initial page:

var app = angular.module('myUniqueApp', ['ngRoute','ngAnimate','customDirectiveModal']);
app.config(function($routeProvider) {
$routeProvider
.when("/",{
    templateUrl : "template/landing.html",
    controller : "uniqueLandingCtrl"
})
.when("/home",{
    templateUrl : "template/home.html",
    controller : "uniqueHomeCtrl"
})
.when("/post",{
    templateUrl : "template/post.html",
    controller : "uniquePostCtrl"
})
.otherwise({
redirectTo: '/'
});
});

How can I take control of the modal popup? From my HTML code, it currently appears like this:

<div login-custom-modal></div>

I desire to personalize this modal according to my specific needs. For example, if I want to have control over what text is displayed or add new elements, and call/show this popup only when certain conditions in the controllers are met.

Answer №1

In your custom directive, you can implement the modal functionality using built-in Bootstrap methods. The following code snippet demonstrates an example:

link: function postLink(scope, element, attrs) {
    scope.title = attrs.title;

    scope.$watch(attrs.visible, function(value){
      if(value == true)
        $(element).modal('show');
      else
        $(element).modal('hide');
    });

    $(element).on('shown.bs.modal', function(){
      scope.$apply(function(){
        scope.$parent[attrs.visible] = true;
      });
    });

    $(element).on('hidden.bs.modal', function(){
      scope.$apply(function(){
        scope.$parent[attrs.visible] = false;
      });
    });

Note that the $watch function utilizes the Bootstrap method internally. This solution was adapted from the original source available at: Directives for Bootstrap Modal in Angular

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 come (23 == true) is incorrect but (!!23 == true) is correct? After all, there is === for exact comparisons

The question boils down to this: are both 23 and true truthy values? If so, shouldn't they be equal under the loose comparison operator ==? However, there is also the strict comparison operator === for cases where precise equality is required. UPDATE ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Modifying the color of a specific div using jQuery

I am attempting to develop a function that changes the background color of a div when a user clicks on it and then clicks on a button. The value needs to be saved as a variable, but I'm having trouble getting it to work because it keeps saying that th ...

Using Ionic/Angular ion-datetime with specific conditions

In my Ionic app, I have a datetime picker where users can select a time, but with one condition: If the hour is equal to '21', then the minutes must be set to '00' (not '30'). For all other hours, the minutes can be either &ap ...

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Receive live feedback from shell_exec command as it runs

I have been working on a PHP-scripted web page that takes the filename of a previously uploaded JFFS2 image on the server. The goal is to flash a partition with this image and display the results. Previously, I had used the following code: $tmp = shell_ex ...

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

I am having trouble passing a variable into the AJAX URL using JavaScript

Currently, I am attempting to remove an item from mongodb. However, I am encountering difficulty passing the id into the URL through the ajax call. Below is my code: $(".delete-item").on('click', function(e, id) { var deleteName = ...

The functionality of Small Caps is not supported by Twitter Bootstrap when using Chrome browser

I am working with a very basic markup <h1> <a href="#"> My Title </a> </h1> and I have this CSS applied h1 { font-variant: small-caps; } You can see the result on this jsfiddle link. The problem arises when u ...

The standard TextField functionality was disrupted by the update to MUI v5

After typing a comment in the TextField and trying to click Done, nothing happens because the TextField still has focus. The first click removes the focus, while a second click is needed to complete the action. <TextField id={'generalCom ...

An issue with npm arises on Windows 10 insider preview build 14366

It appears that npm and nodejs are experiencing issues on the latest Windows version build 1433 When I ran the following command: npm -v events.js:141 throw er; // Unhandled 'error' event ^ Error: This socket is closed. ...

The console is displaying the array, but it is not being rendered in HTML format in AngularJS

Can you please review my App.js file and let me know if there are any mistakes? I have provided the necessary files index.html and founditemtemplate.html below. Although it is returning an array of objects in the console, it is not displaying them as inten ...

Where can I locate the list of events supported by CKEditor 4?

Looking for the list of available events I attempted to locate the event list in the official documentation, but unfortunately came up short. I resorted to searching through the source code using .fire("/s+") to identify all available events. However, thi ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...