Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it to interact with my JavaScript code?

Any suggestions on how to achieve this?

As a side note, I attempted to add the ng-controller attribute dynamically to the element, but unfortunately, it did not produce the desired result.

Answer №1

In order to achieve this, it is necessary to compile elements.

HTML

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="main.css" rel="stylesheet" type="text/css" />
    <script src="main.js"></script>
<meta charset=utf-8 />
<title>Angular JS</title>
</head>
<body ng-controller="parentCtrl">
    <button ng-click="setCtrl2()">Set Controller</button>
    <div id="placeholder">
        <span></span>
        <select>
            <option></option>
        </select>
        <span class="input-append">
            <input id="add" type="text" placeholder="Another one ?" ng-model="addName" />
            <input type="submit" class="btn btn-primary" ng-click="addRow()" value="+ add" />
        </span>
    </div>
</body>
</html>

Javascript

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

angular.module('app').controller('ctrl', function($scope) {
      $scope.rows = ['Paul','John','Lucie'];
        $scope.name = 'Jack';

      $scope.addRow = function(){
        $scope.rows.push($scope.addName);
        $scope.addName = "";
          console.log($scope.rows);
      };
})
.controller('parentCtrl', function($scope) {
    $scope.setCtrl2 = setCtrl;
});

function setCtrl() {
    var elem =  document.getElementById('placeholder');
    elem.setAttribute('ng-controller', 'ctrl');
    var eSpan = elem.children[0];
    var eSelect = elem.children[1].children[0];
    eSpan.setAttribute('ng-bind', 'name');
    eSelect.setAttribute('ng-repeat', 'row in rows');
    eSelect.setAttribute('value', '{{ row }}');
    eSelect.setAttribute('ng-bind', 'row');

    var injector = angular.element(elem).injector();
    var compile = injector.get('$compile');
    var rootScope = injector.get('$rootScope');
    var result = compile(elem)(rootScope);
    // When outside of AngularJS you need to call digest
    // rootScope.$digest();
}

For more information, visit: http://codepen.io/skarllot/pen/LVKpgd

Answer №2

Have you checked previous questions before? I came across two that might help with your question:

Learn how to load an AngularJS controller dynamically

Understanding how to bind an AngularJS controller to dynamically inserted HTML

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

An error was encountered with Ajax and JSONP due to an unexpected token causing a SyntaxError

Currently attempting to retrieve information from the host at 000webhost The data is in JSONP format: { "categories": { "category": [ { "name": "Android", "parent": "Computer Science", "ID": "2323" }, { ...

Combining Data Structures in Javascript for Visualization in VueJS

Welcome to my first time asking a question. I am currently working on integrating data from two different API endpoints served by a Django Rest Framework backend and displaying it using VueJS on the frontend. The main issue I'm encountering is how t ...

What is the process of converting code to JavaScript and React?

There are two methods defined as shown below. const handleClick = React.useMemo(() => !isRunning ? (items: string | string[]) => { if(Array.isArray(items)){ startRun({ items: items }); } else ...

Update your Selenium WebDriver Manager using npm

When attempting to update the selenium webdriver using the "webdriver-manager", an error occurred: Error: Got error Error: read ECONNRESET from https://selenium-release.storage.googleapis.com/2.48/selenium-server-standalone-2.48.2.jar Error: Got error Err ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

I recently developed a T3 stack project and am currently attempting to configure a next JS middleware, however, I am encountering issues with it not triggering as expected

Having issues with my T3 stack app where the next js middleware is not triggering. I've placed a middelware.ts file in the root directory. middleware.ts // middleware.ts import { NextResponse } from "next/server"; import type { NextRequest ...

Strategies for ensuring a promise is fulfilled before moving on to the next iteration in a never-ending for loop in JavaScript

I've been exploring ways to ensure that a promise is resolved before moving on to the next iteration in a for loop. One suggestion was to use the setInterval() function instead of a for loop, but this isn't ideal since it's hard to predict w ...

The function is not recognized in C# programming language

Whenever I try to trigger functions by clicking buttons, nothing seems to happen and an error message appears in the console. Uncaught ReferenceError: AddressInputSet is not defined at HTMLButtonElement.onclick I'm new to this and could use ...

Guide on adjusting shadow intensity with a Directional Light on a BoxGeometry in Three.js

I've been working on adjusting the light and shadow settings for Box Geometry. Specifically, I am using a Directional light with a certain intensity level. However, I've noticed that when I decrease the intensity, the plane appears darker while t ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

Column on the far right of the grid with a frozen position

I need to design an Angular grid where the last column remains frozen. This frozen column should display the summation of all row values, and the last row should be editable. I am able to create the Angular grid itself, but I am struggling with how to stru ...

What is the reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Enhancing OpenSeadragon images with custom overlays and managing error messages

Currently, I am experimenting with the Basic Single-Row Tile Source Collection example using the same configurations and tile sources outlined in the example. However, I am encountering difficulties in adding overlays to the first and second images as int ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

Expanding a string by adding numeric characters using JavaScript Regular Expressions

Can you increment a numeric substring using regex/replace? For example, if the end of a string (like window location) contains #img-{digit}, is it possible to use regex to replace the digit with +1? I know how to match the hash, but extracting the number, ...

In React js, what is the best way to retrieve the first unique ID element as well as the last unique ID element from an

Hey there, I'm working with some data and you can find the link to it here: https://stackblitz.com/edit/react-26pgys. My goal is to filter the JSON and extract the first unique ID along with the last unique ID. I've already made an attempt at fi ...

What exactly is the concept of lazily installing a dependency?

The website here contains information about the changes in Ember 2.11. Ember 2.11 now utilizes the ember-source module instead of the ember Bower package. In the upcoming Ember CLI 2.12 release, Bower will no longer be installed by default but will only ...

When jQuery updates the content, the div content disappears temporarily

I am currently using jQuery to generate HTML by fetching data from a JSON file. Below is the code snippet where I create the HTML: $(document).ready(function () { $('#searchForm').submit(function () { var entry= $("#searchFo ...

JavaScript not functional, database being updated through AJAX calls

I have created a game using Phaser, a JavaScript library for games. Now I am looking to implement a score table using JS/PHP. My main focus is on transferring a variable from JS to PHP in order to update the database. I have researched numerous topics and ...