1

I have a question relating assigning a variable vs a new object in scope. Take the plnkr example where I have an on/off canvas menu (http://plnkr.co/edit/bJsDuEd9QPG65HMdkAIQ?p=info). Within the mainCtrl defined in the app.js file. I have defined two scope variables as follows:

$scope.navLeft= false;  
$scope.navRight=false;

In this example I use ng-include which links to the navbar.html that contains the navbar and left nav menu toggle switch. This toggle doesn't work, where I understand ng-include creates a new scope.

However in the next plnkr example (http://plnkr.co/edit/PQOeT61mjZdDWwSbjlyQ?p=preview) the navLeft and navRight are defined within a new object.

 $scope.nav = {

    navLeft:false,//default navLeft menu off
    navRight:false//default navRight menu off

  };

This works, that is the navLeft menu is toggled on/off. Question I have, why does the latter example which uses a new object, does not create a new scope thus work? But the first example which defines the navLeft & navRight variable using '=', why does it create a new scope and therefore not work? Appreciate any comments on the topic. Thanks

Ka Tech
  • 8,937
  • 14
  • 53
  • 78
  • 1
    Anyway - using of objects is better way because U can share objects between scopes, services and not-angular modules of your applications. Scope variables are not so flexible. – comdiv Feb 03 '15 at 03:26
  • Related: [AngularJS: dot in ng-model](http://stackoverflow.com/a/17607770/2845029) – aarosil Feb 03 '15 at 03:27
  • @ФагимСадыков but these are both `$scope` variables – aarosil Feb 03 '15 at 03:30
  • Thanks @ Фагим Садыков. So to clarify, objects are more easily shared than scope variables. – Ka Tech Feb 03 '15 at 03:38
  • Using objects also provide more context, make the code easier to read, and avoids any reference issues that may occur without "dotting". – Wayne Ellery Feb 03 '15 at 03:48
  • 3
    Hard to get a better explanation than **[this one](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs)**. – PSL Feb 03 '15 at 03:49
  • 2
    And keep in mind that this is not an angular specific design or choice, it is the way Javascript itself is works and is interpreted. I +1 the link provided by PSL. – floribon Feb 03 '15 at 04:18

0 Answers0