Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS,

<script type="text/javascript">
    angular.module('app').controller('add', ['$scope',function($scope) {
           $scope.name = "Bonita Ln";
    }]);
</script>

The corresponding Javascript code to access $scope variable member name is as follows:

<div ng-app="app" ng-controller="add">
   <script type="text/javascript">
       var dom_el = document.querySelector('[ng-controller="add"]');
       var ng_el = angular.element(dom_el);
       var ng_el_scope = ng_el.scope();
       var name = ng_el_scope.name;
   </script>
</div>

Here is an example of angular code that accesses the ng-init variable name using angular expression:

<body ng-app="">
    <div ng-init="name='Bonita Ln'">
        {{name}}
    </div>
</body>

Now, the question arises, how can one access the ng-init variable name using JavaScript?

Answer №1

To access the variable $scope.name in your controller, it must be defined within your scope.

<div ng-init="name='Bonita Ln'">
  {{name}}
<div ng-controller="MyCtrl">
  Hello, {{name2}}!
  </div>
</div>


angular.module('myApp',[]).controller('MyCtrl',function($scope) {
    $scope.name2 = $scope.name;
})

This method works when you define the name in the parent scope of the controller and have it inherited.

If the HTML template for the same controller looks like this:

<div ng-controller="MyCtrl">
<div ng-init="name='Bonita Ln'">
  {{name}}
Hello, {{name2}}!
  </div>
</div>

It will not work because the variable was undefined when the controller function was invoked.

Answer №2

While you can technically use it in the same way, it's not recommended.

Your question has been downvoted because every line of code provided is considered bad practice. It's hard to determine your end goal, making it difficult to offer better code suggestions. However, I can provide you with some resources that may help improve your coding practices:

  • Shaping up with Angular is a free course from the Angular team, offering valuable insights on using Angular effectively.
  • Papa Johns Angular styleguide provides guidance on writing maintainable code.
  • thinkster.io offers a step-by-step guide for mastering Angular.
  • egghead.io includes a collection of helpful video tutorials.

I understand that this feedback may seem harsh, but adhering to standardized Angular practices and style guides will benefit you in the long run. Remember, in Angular, your code should be separated from the DOM; utilize directives like ng-click instead of attaching eventListeners to DOM elements.
(note: there may be exceptions to this rule)

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

Deleting the stylesheet exclusively within the confines of the React application window

Here is an image that will help illustrate the issue: https://i.stack.imgur.com/VA7fw.png If you want to check out the code sandbox for this problem, you can visit: https://codesandbox.io/s/annoying-stylesheet-2gpejc?file=/public/index.html I am current ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...

Encountered a login issue when attempting to access the localStorage

Any suggestions on resolving this error? Encountering a QuotaExceededError with DOM Exception 22 This issue arises when attempting to access the localStorage and assign data to the header. Currently working with Angular 2 on the client side using Type ...

Reloading a Nuxt.js page triggers the fetch function

I'm facing an issue with nuxt.js fetch(). Whenever I reload the page, it does not fetch the data again. It only fetches if I come from a router link. How can I force it to actually refetch the data from my API? export default { async fetch() { ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

The kendo-grid-messages are utilized across all columns

I encountered an issue while working with the following code: <kendo-grid-column field="isActive" [title]="l('Status')" filter="boolean"> <kendo-grid-messages filterIsTrue="Yes" filterIsFalse=&qu ...

Positioning of the dropdown in Material UI AutoComplete menus

Is there a way to turn off autocomplete auto position? I would like the autocomplete options to always appear at the bottom. Check out this link for more information! ...

Whenever attempting to choose a rating, the MUI dialog continuously refreshes and resets the selected rating

I'm facing an issue with my MUI dialog where it keeps refreshing and resetting the selected rating every time I try to rate a movie. Any assistance on this matter would be highly appreciated. The RateWatchMovieDialog component is designed to display ...

Discover and transform any strings that begin with http & https into clickable links

Can I use jQuery to search a paragraph for all strings that begin with http & https and turn them into clickable links? I have my Twitter feed displayed on my website, but any lines starting with http & https are shown as regular text. Is it feasible to t ...

Creating a plotly.js integration for nuxt SSR: A step-by-step guide

Currently facing issues with setting up plotly.js in my nuxt project. Despite trying various approaches, I keep encountering the error message self is not defined. Installing both plotly.js and plotly.js-dist did not resolve the issue. My attempt to creat ...

Mastering End-to-End Testing in AngularJS with Protractor

I am struggling to extract the last row of a ng-repeat table in Protractor for testing purposes. My goal is to verify that an object created in a previous test run is displayed correctly. So far, I have managed to retrieve all the text in the last row but ...

Sending the "Enter Key" using JavaScript in Selenium can be achieved by utilizing the "executeScript" function

I'm currently developing an automation flow using IE 11 with Selenium and Java. On a particular web page, I need to input a value in a Text Box and then press Enter. I have successfully managed to input the values using the following code: // The &ap ...

Using Jquery to transfer text from a form to a DIV and ensuring the final character is verified

Users can input their name on my HTML form, which will then be displayed in a DIV as part of a book title. The book title includes apostrophes (e.g. Amy's Holiday Album). However, if the user's name ends with an S, I do not want the apostrophe ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

Display the length of an array using AngularJS

Hey there, I'm currently having an issue with printing a list where each entry is supposed to follow the format "element X of TOTAL". However, instead of displaying the total value, it appears as blank text. It seems like a simple mistake, but for som ...

Unveiling the Potential of AngularJS through Dynamic Testing with FabricJS/Canvas

What are the best practices for writing tests for FabricJS in a directive and service? Check out this example app: I've been struggling to make progress with my tests and resorting to some less-than-ideal solutions. My goal is to integrate this powe ...

Creating a dynamic multi-series line chart in D3 version 4 that incorporates data points with matching colors to their respective lines

In my attempt to enhance a multi-series line chart with D3 V4 in Angular-cli, I have encountered a challenge. Below is the code snippet of what I have been working on. var lookBookData = z.domain().map(function (name) { return { name: name, ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Enhancing Communication Between JavaScript and PHP

Positioned within my form is an input field where users can enter their postcode. The shipping cost for their order will be determined based on this postcode, utilizing PHP to assign different costs depending on the zone. After the user enters their postc ...