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

What could be causing the data to be cut off to zero in my controller?

Currently in the process of migrating an application, and I've encountered some code that was already functioning properly. I have an Angular function that generates random AVL input to test my API. $scope.createAvl = function () { console.log($ ...

Encountering a problem when attempting to open a model dialog in AngularJS

I'm looking to implement a modal dialog in my project, but I seem to be encountering some issues. Here's what my HTML code looks like: <div ng-controller="bodyController"> <!-- This html would live at the path specified in the contr ...

Using jQuery ajax links may either be effective or ineffective, depending on the scenario. At times

Can someone please assist me in understanding why an ajax link may or may not work when clicked? It seems to function intermittently. window.onload = function(){ function getXmlHttp(){ ...... // simply ajax } var contentContainer = ...

The default value of the select option will not be displayed upon loading and will also not appear when another option is selected

I created a form using vue.js that includes a select option dropdown. However, the default value does not display when the form loads, and when a new option is selected from the dropdown, it also does not show. When I use v-for to loop through all options ...

Having difficulty retrieving additional arguments within createAsyncThunk when dispatched

When attempting to update the user thunk action by passing an axios instance as an extra argument, I am encountering difficulties in accessing the extra argument. Despite being able to access other fields such as getState</coode> and <code>disp ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

Adding a class-matched element with a corresponding ID

Despite finding similar questions, I am still unable to achieve the desired outcome. Here is a list: <ul> <li class="class1"></li> <li class="class2"></li> <li class="class3"></li> <li class="class4"&g ...

Facing Issues with User.update in Mongoose and MongoDB

I have been struggling to create a new collection and push it into a specific user's collections array. Despite researching various stackoverflow posts, I am unable to achieve this using either User.update() or User.findOneAndUpdate(). I can confirm t ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

The process of rendering children elements in React

I have a question about managing children components in React. While there are resources available explaining this concept, I believe a more detailed explanation would be helpful. Let's consider the structure of my React component tree, which looks l ...

The Journey of Processing Forms in AngularJS

I've been struggling to handle the data submitted from a form, specifically when dealing with customers registering multiple guests at different hotels. I've searched extensively on this platform and spent countless hours reading through various ...

Are you struggling with Grails - Ajax submission not functioning properly?

Trying to update a div when a form is submitted, but it seems like something is missing. Here's the HTML code: <%@ page contentType="text/html;charset=UTF-8" %> <html> <head> <meta name="layout" content="main" /> ...

What are the ways to activate an element in vue js?

Is there a way to modify the code so that the function triggers with just one click instead of two? export default { methods: { remove(){ $('.remove-me button').click( function() { removeItem(this); }); ...

delivering information to angular-ui modal while operating control as vm

I am facing an issue with passing an object to a modal controller. I have tried various approaches and here is my final code. Although the object is passed successfully, a significant error appears in the console. Error: [$injector:unpr] Below is the cod ...

Uploading files seamlessly without the need for refreshing the page

On my HTML page, I have a form input that allows users to upload a file. Here is the code snippet: <form action = "UploadFile.jsp" method = "post" target="my-iframe" enctype = "multipart/form-data"> <input type = "file" name = "file" ...

Tools needed for Angular project development

Currently, I am engaged in a project using AngularJS on a Windows 7 computer. My desire is to be able to seamlessly transition between working at the office and working from home or any other location. If I have everything installed in a folder named C:/C ...

Is there a performance benefit to using node.js over client-side JavaScript in comparison to Chrome/V8?

Currently, I am working on a client-side javascript application for image manipulation. However, some of the operations are running quite slowly in the browser, taking about 2-3 seconds to complete. To address this issue, I am considering implementing a s ...