Search code examples
angularjsangularjs-rootscope

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

Solution

  • 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";