khawarizmi
khawarizmi

Reputation: 732

AngularJS Code Understanding

Can someone please help me explain this code segment in AngularJS

$rootScope.compiledScope = $scope.$new(!0, $rootScope), $scope.variable = "someValue";
  1. What is $new operator serving here
  2. What is !0?
  3. How , is used to separate two statements and assign it to one variable on left

Upvotes: 2

Views: 80

Answers (3)

Subash
Subash

Reputation: 7256

From the documentation, $new function accepts 2 parameters.

First Part:

$new(isolate, parent);

isolate : If true creates isolate scope for the new scope that you are creating. Which basically means it wont inherit from the parent scope. It will inherit from the parent scope but parent scope properties wont be visible to it.

parent : $scope that will be the parent of newly created scope.

!0 : In most programming languages 0 == false. And negating that will give you true.

So deciphering the first part of your code:

$rootScope.compiledScope = $scope.$new(!0, $rootScope)

Add property called compiledScope to your $rootScope whose value will be a new isolate scope whose parent is $rootScope.

isolate scope : Scope that does not prototypically inherit its parent scope. Its is basically an empty scope and non of its parent's properties are visible to it.

Second Part

$scope.variable = "someValue";

Attach a variable to the $scope and sets its value to someValue. And the comma in between just separates 2 statement and is same like doing:

$rootScope.compiledScope = $scope.$new(!0, $rootScope);
$scope.variable = "someValue";

Upvotes: 1

urpalreloaded
urpalreloaded

Reputation: 506

Q1: $new is used to create a new scope

Q2: '!0' is nothing but 'true'. In this case, this would make Angular to create a new scope that doesn't prototypically inherits parent scope ($rootScope in this case).

Q3: It is a valid JS syntax and at the end of execution $rootScope.compiledScope would have a new isolated scope and $scope.variable would have someValue

Upvotes: 1

Shota
Shota

Reputation: 7330

As documentation says, the first parameter, in your case: !0 = true :

If true, then the scope does not prototypically inherit from the parent scope. The scope is isolated, as it can not see parent scope properties.

the second parameter, in your case $rootScope:

The Scope that will be the $parent of the newly created scope. Defaults to this scope if not provided.

So $scope.$new(!0, $rootScope) will create the fresh new child scope of rootScope.

3) Here a as new scope is created it assigns $scope.variable to the new scope, so this variable is only available in this new and the parent scope.

Upvotes: 1

Related Questions