Tuesday, 4 April 2017

$scope vs. $rootScope


$rootScope is available globally for all the controllers.
$scope is available for a controller and its children.

JS
app.controller("helloController", function ($scope) {
   $scope.helloMessage = "Hello"
;

       $scope.rootMessage = "Welcome";
});

app.controller("byeController", function ($scope) {
   $scope.byeMessage = ""Bye, See you
";
});




HTML
<div ng-controller="helloController"
    Root message : {{ rootMessage }}  <br/>
    Hello message : {{ helloMessage }}  <br/>
    Bye message : {{ byeMessage }}
</div>
 
<div ng-controller="byeController">
    Root message : {{ rootMessage }}  <br/>
    Hello message : {{ helloMessage }}  <br/>
    Bye message : {{ byeMessage }}

 </div>

Output
Root message : Welcome
Hello message : Hello
Bye message :


Root message : Welcome
Hello message :
Bye message : Bye, See you



Handle unavailable properties


Check the property for undefined value and show the message using ng-show
 
<div ng-controller="helloController"
    Root message : {{ rootMessage }}  <br/>
    Hello message : {{ helloMessage }}  <br/>
    Bye message :
       <span style="color:red" ng-show="byeMessage == undefined">
           Bye message is undefined.
       </span>
</div>


Output
Root message : Welcome
Hello message : Hello
Bye message :
Bye message is undefined.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.