SlashJ
SlashJ

Reputation: 807

ng-switch not reacting to dynamic value change

i am new and experimenting with AngularJS.

That being said, i am unsure how to bind value to an ng-switch and change between views dynamically by changing the 'activeView' variable value.

Side note: is it a good practice to switch between views like this? The views are different ways of displaying the same data so its pretty much the same context and i did not see a reason to create a different page for the two views. Oh and the views contents are actually directives components.

the html:

<body ng-controller="SomeController as vm">
    <div ng-switch="{{vm.activeView}}">
        <div ng-switch-when="someView">
            some directive component
        </div>

        <div ng-switch-when="anotherView">
            another directive component
        </div>

        <div ng-switch-default>
            nothing to show
        </div>
    </div>
</body>

the controller:

(function () {
'use strict';

angular
    .module('app')
    .controller('SomeController', SomeController);

function SomeController() {
    var vm = this;

    vm.activeView = '';

    function setViewType(viewType) {
        vm.viewTypes = viewType;
    }

    setViewType('anotherView');
}
})();

So what happen is that the default switch is visible, event after calling setViewType('anotherView');

Thanks in advance!

Upvotes: 0

Views: 1235

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29846

  1. You don't need the interpolation when using ng-switch ({{vm.activeView}}).
  2. You aren't assigning vm.activeView with a value.
  3. Your angular.module doesn't have a dependency array. If this is the place that you define your module then add it.

    (function () {
    'use strict';
    
    angular.module('app', []) // add the dependency array
        .controller('SomeController', SomeController);
    
    function SomeController() {
        var vm = this;
    
        vm.activeView = 'anotherView'; // change this
    
        function setViewType(viewType) {
            vm.viewTypes = viewType;
        }
    
        setViewType('anotherView'); // this changes the viewTypes prop
    }
    })();
    

Check on this JSFIDDLE.

Upvotes: 2

Related Questions