1

I am quite new new to AngularJs. In my controller i have a $rootScope variables which i want to assign a value dynamically depending on conditions. Following is my controller code:

controller(){

$rootScope.tab1;
$rootScope.tab2;
$rootScope.tab3;
$rootScope.tab3;
$rootScope.tab4;

$scope.changeVal("tab2");

$scope.changeVal=function(tabname){
    vm.tabs=['tab1','tab2','tab3','tab4','tab5'];
    angular.forEach(vm.tabs, function(val) {
        if(tabname===val)
        {
            //here $rootScope.tab2 value should be changed
            //something like bellow
            $rootScope.{{tabname}}="myValue";
        }
        else{
        $rootScope.$eval(val)="";
        }
    });

}

}

I know that , by applying multiple if or switch conditions this can be done. But, finding some optimized solution. Any help would be appriciated. Thanx in advance.

1
  • 1
    The following remarks answer your question, but why use $rootScope? Is using a local $scopenot enough? Try limiting the digest cycle if possible. Another way to store application variables is to use services (singleton). Commented Feb 8, 2017 at 12:29

2 Answers 2

1

Why don't you just use

$rootScope[tabname]="myValue";

$rootScope is like an object in angular on which you can add properties and access properties like how you do with plain old javascript.

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

Comments

0

root scope is just another javascript object, so you'd do

$rootScope[tabname]="myValue";

(That said, it's generally not a great idea to stuff a lot of data directly into $rootScope, that's the Angular equivalent of using global variables for everything...)

4 Comments

i agree with you. Actually this is sample code, i have to use these variables in all over my application, so they are global ones.
If you need to share data across the application, consider using a service instead of root scope.
Yes. But for a moment your solution is not working. I think it thinks that expression as array.
That syntax works for objects too. for example var foo = {}; var bar="baz"; foo[bar] = "bat"; I'm not sure what's going wrong for you, can you be more specific about what happened? "That's not working" doesn't give much to go on

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.