Is the angular controller as syntax still necessary, or is $scope only needed for special occasions?

I have implemented angular's 'controller as somename' syntax.

Consider the following function as my controller:

function myCOntroller($scope)
{
  $scope.$emit('event');
}

The above function is functioning properly. I attempted the following approach:

function myController()
{
  var reference = this;
  reference.$emit('event');
}

This method did not work. I am able to use reference for data bindings, so why can't I use it for such tasks? I assumed that since reference now contains all the functions that $scope has, $emit would work in this way too.

NOTE: Apologies for the code samples being purely theoretical. This question was posed as a proof of concept without any actual code involved.

Answer №1

As mentioned previously here,

The 'Controller as' feature was introduced as a syntax enhancement in version 1.2 to address issues with $scope and its prototypal inheritance drawbacks.

<body ng-controller="MyCtrl as myCtrl">
...
app.controller('MyCtrl', function () {
  ...
});

This is equivalent to

<body ng-controller="MyCtrl">
...
app.controller('MyCtrl', function ($scope) {
  $scope.myCtrl = this;
  ...
});

While it doesn't completely replace the need for $scope, it does introduce a useful pattern within the controller (unless you specifically require $scope functionality like $on events).

Therefore, utilize this instead of $scope when utilizing it as a model.

Answer №2

The use of "controllerAs" does not equate this with $scope.

Prior to implementing controllerAs in the best possible way, a controller would typically involve utilizing a scope.

angular.module("myApp")
.controller("myController", ["$scope", function MyController ( $scope ) {
    var myControl = { data: 123 };
    $scope.myControl = myControl;
}]);

This results in HTML that resembles

<div ng-controller="myController">{{ myControl.data }}</div>

When using controllerAs, this refers to the controller itself (and not the $scope), eliminating the need to add properties to the $scope most of the time, unless for certain requirements such as events or directives with attributes.

this.$scope == $scope

angular.module("myApp")
.controller("myController", [function MyController ( ) {
    var myController = angular.extend(this, { data: 123 });
    myController.$scope.$emit( /* ... */ );
}]);

This allows you to write

<div ng-controller="myController as myControl">
    {{ myControl.data }} <!-- === $scope.myControl.data -->
   <!-- "as" sets the name of the controller, on the scope -->
   <!-- $scope.myControl.$scope === $scope -->
</div>

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 is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance. Currently, only the 'All' option is working for applying any filtering logic. Here is how my HTML looks like with the filt ...

Is it possible for me to create a hyperlink that directs to a javascript function?

Here is the code I am currently using: <input class="button" type="button" value="Mark" onClick="doCheck('mark');" \> However, I would like to replace the button with a hyperlink using the <a> tag. Is it possible to achieve ...

Is there a way to extract a username from LDAP?

Can you help me understand how to dynamically retrieve a username from LDAP? In the code snippet below, I have hardcoded the username as 'smith2': $_SERVER["REMOTE_USER"] = 'smith2'; $param = $_SERVER["REMOTE_USER"] By using this appr ...

Establish the starting time for the timer and use the setInterval() function according to the seconds stored within the object

How can I configure the values of timerOn, timerTime, and timerStart to make the watch start counting from 120 seconds? Currently, the clock starts counting from 3 minutes and 22 seconds, but it should start from 2 minutes. You can find all the code here: ...

Issues with excessive firing of JQuery blur and hide functions

I am currently using jQuery v1.11.2 and have set up a basic JSFiddle at this link (http://jsfiddle.net/k1g3upbv/). The layout may not be ideal in JSFiddle due to the integration of Twitter Bootstrap within my project. I quickly put together the JSFiddle, o ...

Clicking on the mail icon will open the mail with the associated mail id

When the mail icon is clicked, the mail will open with this email address. I am currently working on a project where clicking the mail icon will redirect to the mail signup page with the corresponding email address. In the image below, the red border ind ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

What is the best way to incorporate an AngularJs theme into Django?

My experience in AngularJS and Django is at a beginner level, but I am eager to develop a web application using both platforms along with Postgre SQL as the database. I have a specific AngularJS theme that I would like to seamlessly integrate with my Dja ...

I'm having issues with my page due to the ui.bootstrap uibModal in Angular

I have been diving into learning Angular recently, and while following a tutorial, I realized it was based on an older version of Angular. This has caused issues with the part of the tutorial that covers using ui.bootstrap. Currently, I am working with An ...

Tips for implementing the new useState value in your code

Using DataGrid Material UI, I am facing an issue where the selected row is not being deleted when clicking on the delete button. The problem arises from setting the ID value in the useState hook and encountering asynchronous behavior in deleting the rows. ...

Associating user input information with an AngularJS object

Currently, I am working on a project that involves inputting a user's ID, first name, and last name. Once the input is received, a user object is created and stored inside the logins array. My goal is to display each new user as the next item in an u ...

Dealing with substantial ajax responses using JavaScript

Currently, I am in the process of developing a website that utilizes jQuery File Tree. However, there is an issue with the enormous size of the AJAX response from the server - 900 KB and containing approximately 70,000 'files' (which are not actu ...

Using jQuery to scroll within a table

I am currently working on a project that involves displaying specific data rows. To achieve this, I have decided to use a table. For a better understanding, you can check out a table demo here. The issue I am facing is that whenever I change the selected ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

How to store data in MongoDB without relying on specific request bodies

I realize that I can simplify the code: var event = new EventModel(req.body); event.save....... If the input names match the attribute names in my database, mongoose can save by simply passing req.body. However, there is an issue with handling dateO sep ...

Searching for elements by tag name in JavaScript

Recently, I attempted to create JavaScript code that would highlight an element when a user hovers their cursor over it. My approach involves adding an event listener to every child within the first "nav" tag in the current document: let navigation = docum ...

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...

"Graphs not Displaying Properly in ChartJs

Seeking assistance with rendering a chart inside a bootstrap popover. Despite various debugging attempts, the chart refuses to render. Any help or insight would be greatly appreciated. Below is my HTML code: <div id="popover-content" style=&qu ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...

The HTML button fails to respond when clicked

My website development process has hit a snag with the header buttons not functioning properly. I suspect the issues lie within lines 12 to 15 of the code snippet below: <!DOCTYPE html> <html> <head> <script src="https: ...