Building a personalized Directive in Angular: A step-by-step guide

I attempted to implement a sample pagination feature by creating a directive like the following (I am not sure if it is correct):

(function() {
app.directive("myPagination", function() {
    return {
        restrict: 'E',
        templateUrl: 'pag.html'
    };
 });
})();

The content of my pag.html file is as follows:

<ul class="pagination" ng-controller="PagingController">
<li ng-repeat="x  in pageing" ng-click="change(x.pageno)"><a href="#">{{x.pageno}}</a></li>
</ul>

My PagingController looks like this:

 app.controller('PagingController', function($scope) {
    $scope.$on('pageinfo', function(event, args) {
        $scope.numbtn = args.numbtn;
        $scope.totaldata = args.totaldata;
        $scope.selet = args.selet;
        $scope.starter();
    })

    $scope.starter = function() {
        $scope.pageing = [];
        let i;
        for (i = 0; i < $scope.numbtn; i++) {
            $scope.pageing[i] = i;
        }
        console.log($scope.pageing);
    }
    $scope.change = function(btnclk) {
        alert(btnclk);
    }
});

In my index page, I tried using

<my-pagination></my-pagination>
, but the problem is that nothing is being displayed and there are no errors. Can anyone help me correct this issue?

Answer №1

Include the PageingController controller within the directive instead of in the template itself

(function() {
app.directive("myPagination", function() {
    return {
        restrict: 'E',
        templateUrl: 'pag.html',
        controller : 'PagingController'
    };
 });
})()

View Demo

Ensure that the subscriber event $on is being executed, otherwise the page array will be empty

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

Middleware in the form of Try and Catch can be utilized to handle errors and

Currently, I am working on developing a backend using node.js with Express. My main goal is to effectively handle any potential status 500 errors that may arise. router.put('/test', async (req, res) => { try { return res.send(await r ...

Error on AngularJS: [$injector:unpr] Provider unknown: $timeOutProvider <- $timeOut <- notification

I am encountering the following error and I am unsure of the reason: Error: [$injector:unpr] Unknown provider: $timeOutProvider <- $timeOut <- alert controllers\register.js angular.module('testApp') .controller('RegisterC ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with I ...

A step-by-step guide on modifying the box-shadow color using jquery

I have developed some JavaScript code that adjusts the box-shadow of buttons to be a darker version of their background color. This allows users to dynamically change the button background colors. The current code successfully changes the box shadow based ...

javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using. function HasMixedCase(passwd){ if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) return true ...

The issue of controller inheritance not functioning properly when using the controller as syntax has

Here is the basic structure of the HTML: <data> <definition-data></definition-data> </data> In my data template file, I have the following code that works as expected: <div ng-controller="dataCtrl as dataitems" ng-cloak> ...

When I try to execute a mutation with Apollo and React, I encounter a 400 error. It could be due to a

Every time I try to perform a mutation, I keep getting a 400 error code for some strange reason. Here is my httpLink code snippet: // ApolloProvider.js const httpLink = createHttpLink({ uri: 'http://localhost:3000/graphql', }); const client ...

Renew the Look of Dynamic HTML with Updated Styles

In the middle of my website, there is a console that contains links to dynamically update its content using javascript. Everything works smoothly, but the new HTML added dynamically does not have any styling applied to it. Is there a way to refresh the CS ...

Oops! There seems to be an issue with trying to access the 'map' property of undefined within the render method

While working on my project, I encountered an issue with a table from react material ui. The problem arises when attempting to populate the table with data from the state, resulting in an error message stating "cannot read property 'map' of undef ...

Generate menu options in real-time

I have developed a React single page application using the NASA Picture of the Day API. I am looking to incorporate a drawer feature that displays a history of previously shown images, but only showing their dates. However, I am unsure of how to dynamical ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Tips for accessing touch events within the parent component's area in React Native

I implemented the code below in my React Native app to disable touch functionality on a specific child component. However, I encountered an issue where the touch event was not being detected within the area of the child component. How can I fix this prob ...

Is it possible to pass variables into a factory function?

I have a factory that is a wrapped $resource object and I am trying to include a custom header for http authentication. However, I am struggling to figure out how to pass data into the header. app.factory('SomeFactory',['$resource', fu ...

Transforming a class component into a functional component using React for a session

While working on a React application, I encountered the need for auto logout functionality for inactive users. After referring to this resource, I attempted to convert my class component code to functional components. However, I faced issues as the functio ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

Creating a multiline textarea with ellipsis using ReactJS

Looking to create a component with a multiline textfield that displays ellipsis (...) for text overflow beyond 2 lines. How can I achieve this through CSS only without modifying the actual stored text? Utilizing the React component found at: link Appreci ...

Implementing image loading within an accordion component using React and Material UI

I'm working with a React Accordion component using Material UI. Each time I open a tab in the Accordion, I want to load different images from another div that is located outside of the Accordion. Here is the current code snippet: export default funct ...

Saving information on localStorage is not possible

Recently, I created a demo for a basic Login and Logout application that utilizes an access token. If a user attempts to access another page without logging in (meaning the access token is null), they are redirected back to the Login page. Initially, I use ...