0

I 've just started to study Angular. Consider the following simple template:

<div ng-app ng-init="qty=1;cost=2">
  <b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" data-ng-model="qty">
  </div>
  <div>
    Costs: <input type="number" min="0" data-ng-model="cost">
  </div>
  <div>
    <b>Total:</b> {{qty * cost | currency}}
  </div>
</div>

The attributes values e.g. qty and cost must be stored inside some variables, isn't it? Which ones and how may I access them through the console?

2
  • 1
    You can store them in a controller. Controllers are an essential part of coding with AngularJS. I suggest you read up on AngularJS essentials. Commented Feb 23, 2016 at 11:42
  • $scope.qty and $scope.cost Commented Feb 23, 2016 at 11:42

3 Answers 3

2

In your js file, you can access them with

$scope.qty and $scope.cost

For eg:

Mark your ng-app as myApp and add a ng-controller

<div ng-app='myApp' ng-controller = 'myController' ng-init="qty=1;cost=2">

Create a js file named app.js with below content

var myApp = angular.module('myApp',[]);
myApp.controller('myController', function($scope)
{
    console.log($scope.qty);
    console.log($scope.cost);
});

You can see qty and cost logged in console

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to access them without adding a controller? Just using my plain template without any JS code and being able to see them, somehow, in console?
You can try {{qty}} below your Quantity input. As you type/change value in the quantity text box, {{qty}} updates. You can see it on browser. I am not sure if you can see it on console directly.
1

You will have to create a controller and store these values there.

In your JS file

var app = angular.module('MyApp');
app.controller('MyController', ['$scope', function($scope){
    $scope.qty = 1;
    $scope.cost = 2;
}]);

In your HTML

<div ng-app="MyApp" ng-controller="MyController">
   <b>Invoice:</b>
   <div>
       Quantity: <input type="number" min="0" data-ng-model="qty">
   </div>
   <div>
       Costs: <input type="number" min="0" data-ng-model="cost">
   </div>
   <div>
       <b>Total:</b> {{qty * cost | currency}}
   </div>
</div>

For your second query - detailed post on checking scope variables in Console.

Comments

0

All variables declared in AngularJS app are stored in $scope, you are able to access them trough console.log($scope.qty) from your controller.

However as you are declaring it in your template you by the time HTML has rendered JS is already loaded, therefore console returns "undefined". To understand the concept try:

$timeout(function() {
 console.log($scope.qty) 
}, 400);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.