Search code examples
javascriptangularjsangularjs-scope

Angularjs Concatenate $scope


I like to know if it is possible to concatenate several $scope to make that one.

For example the address of the orginal scope is:

$scope.templates.webapp.dc01[0].value

I would like the DC01 changes according to my event I tried several thing is it does not work.

I tried in a

ng-init="form.template = templates.webapp.{{building}}[0].value"

it does not work.

I tried like this also:

$scope.test = $scope.templates.webapp + '.' + $scope.building + '[0].value';
ng-init="form.template = test"

it does not work well.


Plunk demonstrating the issue: https://plnkr.co/edit/CaWNeIDHe2nFyEgDABvg?p=preview


Solution

  • The problem lies in nesting angular expressions. In provided plunker you're doing:

    data-ng-options="template.value as template.name for template in templates.webapp.{{building}}"
    

    the part template.value as template.name is already an expression and {{building}} is "nested" in it. Such patterns aren't good idea :)

    What you want to do is simply

    data-ng-options="template.value as template.name for template in templates.webapp[building]"
    

    like you would do in plain JS. This way available options in #s-template change in respect to selected building.

    You can read more about angular expressions here


    Edit

    To change selected (default) value upon selecting building you should move the logic from ng-init to testBat function and call it from controller (instead of doing $rootScope.building = "Dc01";). This way selecting building will always select first value from corresponding list.

    Example: https://plnkr.co/edit/Ggv9DSSLtK3TKvKScZgl?p=preview