Executing an external function on an element as soon as it is created in AngularJS: tips and tricks

I am looking to implement a function from an external library that will be executed on each item as it is created in AngularJS. How can I achieve this? Here is the code snippet of my application.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.blocks = [
    {name: 'item #1'},
    {name: 'item #2'}
  ];
});
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script>
  // This function is part of an external library
  // I want to apply it to each block in ng-repeat
  // It manipulates the DOM
  function setupBlock(elm, name) {
    elm.innerHTML = name + ' [ready]';
  }
</script>

<body ng-controller="MainCtrl" ng-app="app">
  <div ng-repeat="block in blocks">{{block.name}}</div>
</body>

Answer №1

Invent a custom instruction that requires an input called name:

.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
      name: '='
    },
    link: function(scope, elm, attrs) {
      // Insert your code here!
      elm[0].innerHTML = scope.name;
    }
  }
})

View a comprehensive example here: http://plnkr.co/edit/3SOWZrRHOldMRUEl7l0Z

Reminder: For any DOM modifications, make sure to utilize directives!

MODIFY: If you want to pass the entire object to the directive, update the scope declaration like this:

scope: {
  block: '=data'
}

Then, in your ng-repeat markup:

<div ng-repeat="block in blocks" my-directive data="block"></div>

Answer №2

Utilize the $rootScope object in AngularJS

[1]: https://docs.angularjs.org/api/ng/service/$rootScope "

[2]: "

For instance, in JavaScript:

(function() {
  var global;

  global = (function() {
    function global($rootScope) {
      $rootScope.view_directory = "something";
    }

    return global;

  })();

  angular.module('yourapplication').run(['$rootScope', global]);

}).call(this);

In CoffeeScript (using ngClassify):

class global extends Run
    constructor: ($rootScope) ->

        $rootScope.view_directory  = "something"

Answer №3

Here is the solution I came up with for my own question, including a complete working code snippet that builds upon the accepted answer.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.blocks = [
    {name: 'item #1'},
    {name: 'item #2'}
  ];
}).directive('externalBlock', function() {
  return {
    restrict: 'A',
    scope: {
      block: '=data'
    },
    link: function(scope, elm, attrs) {
      setupBlock(elm[0], scope.block);
    }
  }
});
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script>
  // This function is from an external library
  // It is used to set up each block within ng-repeat
  // It manipulates the DOM
  function setupBlock(elm, block) {
    elm.innerHTML = block.name + ' [ready]';
  }
</script>

<body ng-controller="MainCtrl" ng-app="app">
  <div ng-repeat="block in blocks" external-block data="block"></div>
</body>

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

Determining the availability of a remote source in React: A step-by-step guide

Is there a way to verify the existence of a remote resource, such as a large zip file, without actually downloading the file? What is the most efficient method for checking the presence of the resource? ...

AngularJS http requests fail to include session cookies when making CORS requests

Here is the script I am using: <script> function eventController($scope, $http) { $http.get("http://example.com/api/Event", {withCredentials: true}) .success(function (response) { $scope.even ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

Navigate to a PDF file from an HTML5 application using PhoneGap by accessing an external link

Can anyone help me figure out what I'm doing wrong here? Essentially, I am trying to open a PDF in Google Viewer: <a id="pdflink" href="https://docs.google.com/viewer?url=http://pdpdpd.pdf" target="_blank">Pdf</a> When it opens in the vi ...

Implications of using literals, objects, or classes as arguments in functions that are called multiple times can have

Context A project I'm working on involves a scenario where a Shape class is triggering a function call SetPosition( x, y ) on a Drawer class. As part of this process, the Drawer class needs to retain the values (x, y) passed through SetPosition. The ...

Disabling the visibility of elements through a transparent sticky-top menu

I'm having an issue with my website design. I have a gradient background and a sticky-top menu on the site. The problem is that when I scroll down, the content appears through the menu, which is not ideal. I don't want to apply the same gradient ...

Using Angular JS: Implementing ng-repeat with a personalized directive and a fluid model

I have a template structured like this: <div class="row search-panel"> <div ng-show="loadingAirports"> <i class="glyphicon glyphicon-refresh"></i> Searching... </div> <div ng-show="noResults"> ...

The service worker is sending out a pair of requests

I have successfully set up a service worker to cache all requests for offline use, but I am experiencing a problem. Every time I load a page, two requests are hitting my webserver: one from the service worker and one from the browser! How can I cache the ...

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...

Invoke a function from a different source in JavaScript

Below is the JS function implemented: function addMemberToLessonDirect(id) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ...

Add a library to a server with npm installation

When needing to incorporate a library like Croppie, the installation process involves using npm or Bower: npm install croppie bower install croppie Given that I am working on a server, I'm uncertain where to install it. Should it be on the server it ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

What is the best way to display a 'confirmed' message on my registration page once a user has submitted their information?

I have set up a nodejs server and developed a registration page using HTML. When users click the submit button, the server I built receives the input data and validates it. If the user is successfully added to the database, I want to display a new message ...

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

Attempting to conceal a div element along with its contents using AngularJS

I am attempting to use AngularJS to hide a div and its contents. I have defined a scope variable initialized as false and passed it to the div in order to hide it. However, the div is still visible along with its content. <script type="text/javascr ...

Utilizing jQuery for displaying or hiding list elements

To view all the code, click on this link: http://jsfiddle.net/yrgK8/ A section titled "news" is included in the code snippet below: <ul id="news"> <li><p>asfdsadfdsafdsafdsafdsafdsafdsafdsa</p></li> <li>&l ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

An issue has been encountered with the Vue Router within the Micro Front End/Web Components setup, displaying the error message: "Uncaught TypeError:

I encountered an issue that I need help with. Here is the scenario: I have built a Vue application called my-admin micro app consisting of 4-5 screens/components (manage user, manage notifications, manage roles, etc.). I created a router.js file where I d ...

What is the best way to choose a date and time in a custom format within my React application?

I'm currently developing the front-end of my application using React. I am looking for a way to capture the date and time in the specific format shown in this image. Any suggestions or solutions would be greatly appreciated! ...

Asynchronous Function Implementation of Cookies in JavaScript

Here's my query: Is it possible to store a cookie within an async function? For example, creating a cookie from this fetch and then accessing it later within the same function while the fetch continues to update the value each time the function is ex ...