Is there a way to dynamically enable ui-sref through element.append in Angular?

I am in the process of developing a pagination directive. Once the total_for_pagination data is filled, the appropriate HTML for the pagination gets generated.

Here's my current HTML structure with a maximum of 50 per page:

<pagination data-number="{{ total_for_pagination }}" data-max="50"></pagination>

Now, let's take a look at my custom directive:

    link: function(scope, element, attrs){
        scope.$watch(function(){return attrs.number;}, function(){
            //A watch is needed because a database query determines the number of elements to paginate.
            var page_element = '<ul>';
            for(var i = 0; i*attrs.max<attrs.number; i+=1){
                page_element += '<li class="pagination"><a ui-sref="users({start: '+i*attrs.max+', end: '+((i*attrs.max)+(attrs.max-1))+'})">'+i+'</a></li>';
            }
            page_element += '</ul>';
            element.append(page_element);
        });
    }

It seems that although the generated HTML looks correct upon inspection, clicking on the ui-sref link does not change the state. However, when I directly place the same code it works fine.

What could be causing this issue? Thank you!

Answer №1

To achieve the desired outcome, it is essential to leverage one of the core features of AngularJS: $compile. You can see this in action in a live working example. The key line responsible for the magic is:

$compile(element.contents())(scope);

The directive definition could look like this:

.directive("myDirective", function($compile){
  return {
    restrict: 'A',
    link: function(scope, element, attrs){
        scope.$watch(function(){return attrs.number;}, function(){
            var page_element = '<ul>'
            +'<li><a ui-sref="home">ui-sref="home"</a></li>'
            +'<li><a ui-sref="other">ui-sref="other"</a></li>'
            + '</ul>';
            element.append(page_element);
            $compile(element.contents())(scope);  
        });
    }
  }
})

This setup will cater to the following states:

  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
  })
  .state('other', {
    url: "/other",
    templateUrl: 'tpl.html',
  })

It fulfills what is needed. You can view the functionality in action here. Additionally, you may find the following topic pertinent: Form Validation and fields added with $compile

Answer №2

My successful method involved declaring an array within the controller/directive and implementing ng-repeat in the HTML list items. By updating the array dynamically, the elements were automatically updated, and the ui-sref functionality also worked seamlessly. In cases where it did not work initially, applying $scope could resolve the issue.

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

The Android smartphone is experiencing issues with the responsive design not aligning properly on the

I'm encountering difficulties with creating a Viewport that functions properly on an android smartphone. My website is fully responsive, scaling down to 480 pixels wide. At this point, a min-width of 480px is set on the body tag. Initially, my viewp ...

How can you use a callback function with the $apply() method in AngularJS?

My goal is to add an object to an array with AngularJS binding to HTML, and then trigger a click function on the newly created element. Here is the code snippet: $scope.fruits = {"orange", "plum", "cherry"}; $scope.add = function() { $scope.fruits.pus ...

difficulties with pagination features in AngularJS

I am experiencing an issue with pagination as I am unable to see the buttons (1,2,3.....) for my pagination using this code <div ng-controller="PaginationDemoCtrl"> <table class="table"> <tr ng-repeat="row in data.slice(((curr ...

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

Placeholder for empty values in Angular UI mask

Currently, I have implemented the angular ui mask directive for a date field. However, it is inserting underscores as a placeholder. Is there a way to display nothing in the placeholder instead? ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Accordion Box glitch detected in Firefox browser

I have been working on a JavaScript function that controls a slide up/down box. However, I've encountered some issues with Firefox as the box only opens and closes once before failing to work properly again. Upon further investigation, it seems that F ...

Is it advisable to authenticate/authorize static files employed in pages that require authentication?

I am in the process of developing a cutting-edge angular 2 application. All back-end functionality is handled through REST API, ensuring seamless communication between the client and server. For enhanced security measures, all APIs that require authentica ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

In Node.js, the `res.send()` function is called before the actual functionality code is executed

As a newcomer to node js, I am currently working on an app where I query the MySql DB and process the results using node js. One issue I have encountered is that if my initial query returns null data, I then need to perform another query and further proc ...

Retrieve checkbox selected value using pug and node.js

How can I retrieve the value of a checked checkbox in order to redirect to (href="/player/edit/:id") or (href="/player/delete/: id"), and obtain the player id for editing or deleting? I have omitted other code details such as app.js which includes the ser ...

Attempting to generate a dynamic menu on a new webpage by pulling data from the WordPress database of a separate site

My goal is to showcase a menu on my webpage using the values extracted from the WordPress database of another website. Here's the progress I've made so far: app.js angular.module('plunker', []).controller('MainCtrl', func ...

Protractor sendKeys method on Modal dialog is failing due to element visibility issues

I seem to be facing a strange issue with protractor. My challenge lies in testing a form that is situated within a modal. Although I am able to verify that the modal is indeed open, I encounter difficulties when attempting to sendKeys to the input fields. ...

How can you retrieve input radio button values using javascript or ajax and display or hide a button accordingly?

I've created a form that includes radio input buttons and a textarea field as follows: <input type="radio" value="2" id="order_status"> Review <input type="radio" value="1" id="order_status"> Accept <input type="radio" value="2" id="or ...

What could be causing the .hover function to malfunction and how can I make it so that the .hover function only applies within the corner radius area?

I am attempting to make circles react to my jquery .hover function. Below is the JavaScript code I am using: jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + ...

Retrieve the Corresponding Content Inside the Div Element

I have a div with text that needs to be matched with comma-separated values: <div class="val"> This is paragraph 1 </div> <div class="val"> This is paragraph 2 </div> Using an Ajax call, I retrieve the ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

Is there a way for me to determine the specific link that I have clicked on

I am implementing a table where users can edit the columns. Each cell contains an <a> tag that triggers a modal to change the value in the database and refresh the page. The issue I'm facing is that once the modal appears, the code doesn't ...