Is it possible to create a dynamic HTML element with an AngularJS Directive without using $scope?

Looking to use This Plunker example code to dynamically add elements to an HTML page using AngularJS. (Make sure to run it in a separate link, not in the editor environment.) This will be my first time working with AngularJS Directives (aside from simple testing). I have a couple of questions regarding this code snippet:

  1. I typically use the Controller as syntax instead of $scope in my controllers. What changes should I make to the sample code above since it uses $compile(...)($scope)?
  2. Is the scope in a Directive related to the controller? If I can remove the scope reference from the controller in this scenario, do I need to make any adjustments to the directive?

Answer №1

1) When using the controller as syntax, replace $compile(...)($scope) with $compile(...)(vm). Also, use vm or this instead of $scope for all functions and variables.

var vm = this;

Therefore, instead of $scope.list, use vm.list and apply the same change for functions.

$scope.do = function() ..

  vm.do = function() ....

2) Include controllerAs in directives like this:

app.directive('myDirective', function () {
  return {
    scope: {},
    controller: function () {
      this.name = 'Elnaz'
    },
    controllerAs: 'ctrl',
    template: '<div>{{ctrl.name}}</div>'
  };
});

If you need to reference an external controller, do this:

app.directive('myDirective', function () {
  return {
    restrict: 'A',
    controller: 'EmployeeController',
    controllerAs: 'ctrl',
    template: ''
  };
});

In your view, make the following changes:

<div ng-controller="myController as ctrl">
   {{ctrl.name}}

   <button type="button" ng-click="ctrl.do()">Do</button>
</div>

Edit: working demo

Answer №2

Solution for the 1st point:

  1. Within the controller, define a variable to represent "controller as";

    let vm = this;

  2. All the properties previously bound to $scope will now belong to vm

  3. In the HTML: Use this syntax to bind controller with div:
    <div ng-controller="customCntrl as vm"
  4. When referencing scope properties in the view, prefix them with vm like this: vm.name
  5. For directives: To bind controller with "controller as":

    app.directive('customDir', function() { return { controller: 'customCntrl', controllerAs: 'vm', ...

                }
            }); 
    

Solution for the 2nd point:

  1. You can still use broadcast and emit on 'vm' like so:

    $scope.$watch('vm.name', function() { $scope.$broadcast('topic-123', 'msg'); });

    To capture it: $scope.$on('topic-123', function(event, msg) {});

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

Is there a way to retrieve real-time information using momentjs in a Vue.js application without needing to refresh the

I have a unique table where I showcase details about a particular website. Among the displayed information is the timestamp indicating when the data was last updated. At the top of the table, my aim is to include an icon that will only appear if the dura ...

The position of the child element is not correct when the parent element is transformed in two dimensions

It's so frustrating when elements with the CSS property 'transform' don't play nicely with embedded elements that have the property 'position: absolute'. It's driving me insane!!! For example, when clicking on a menu ite ...

What is the best method for excluding undefined values from arrays in javascript?

let values = dataSku.map(sku => {return map.skuInfo[sku].description}) If map.skuInfo[sku] can potentially be null or undefined, how can I filter it out? ...

What is the best way to incorporate javascript assets selectively in SailsJS?

How can I selectively include javascript assets in a Sails.js application? For example, if I have an admin page with admin.js in the assets/js directory, how can I prevent admin.js from loading on the public index page? I know I could move the js to the ...

Unable to properly utilize environment variables on Vercel when using Nuxt framework

I'm encountering difficulties accessing my environment variables on Vercel. When I test the site on my localhost, everything works fine; however, once it's deployed to Vercel, the access to environment variables in my components and plugins direc ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

What is the process for linking a ReactJs frontend project folder with a NodeJs backend?

I have a React web application with a crypto portfolio feature and I am looking to establish a connection with the backend server.js. The deployed web app should start from the Node Server. While I am still new to NodeJS, I have attempted solutions like co ...

Deactivate buttons: saving data exclusively for the most recent click

My application has a series of buttons, each representing a channel. When a button is clicked, it triggers a function in the MainController with the corresponding ID as a parameter. Next to the channel buttons, there is an input field where I can enter in ...

Set a click listener on a button within Ext.window.MessageBox

Currently, I am dynamically generating a message box using Ext.window.MessageBox. var msgBox = Ext.create('Ext.window.MessageBox', { title: '', //message in window msg: 'message text', icon: ' ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Is it recommended to exclude the package-lock.json file from being tracked in version control by adding it to

By running the npm install command, a file named package-lock.json is generated to secure the versions of dependencies in a project. This feature has been available since Node.js v8.0.0 and npm v5.0.0. Although Node.js and npm advise on committing this fi ...

Assigning text to textarea according to the content in the input field

Need help with input fields and textarea input(ng-model='form.firstName', name='firstName', id='familyName') and input(ng-model='form.lastName', name='lastName') I also have a textarea field textarea(i ...

When two dynamically sized divs are contained within a parent div with a maximum height, the second div should be positioned at the bottom

My outer div has a maximum height of 800px. Depending on the results of a MySQL query, there could be one or two inner divs nested within the outer div. The second inner div must always be fixed to the bottom of its parent. I know how to achieve this usin ...

What is causing the permissions in firestore to not function properly?

My custom code changed(){ let reference = db.collection('messages').orderBy('timestamp') // listen for changes to the 'messages' collection reference.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => ...

RSS feed showing null xml data with jQuery

Working on coding a straightforward RSS feed utilizing jquery and pulling data from Wired. Everything appears to be functioning correctly, except for one issue - after the description, an unknown value of NaN is appearing in the result. It seems to be comi ...

MongoDB failing to store model information

As I dive into practicing with APIs to hone my skills in creating models and routes, I find myself stuck on getting my initial route to successfully save data to my MongoDB database. When testing with Postman, I encounter the following error: { "message" ...

Error: The TVJS Framework encountered a JSON Parse issue due to an unexpected EOF

I am currently developing a TVML application specifically for Apple TV. However, when I attempt to execute this code to send a request to a remote server, I encounter the following error: SyntaxError: JSON Parse error: Unexpected EOF. My goal is to run thi ...

How can I update the color of table rows after the ng-repeat has been implemented?

My current project involves Django, Python, and a bit of AngularJS. I have a dynamic history table that grows as data is added. I am looking to apply some simple CSS to this table - specifically, I want to give every even-numbered row a black background ...

Attempting to employ $set in conjunction with stringify, unfortunately without success

I am currently trying to utilize this function to edit a specific space in my MongoDB database. However, being new to this, I am struggling to understand what is going wrong. The error message "missing ) after argument list" keeps appearing. Any help and ...