Search code examples
javascriptangularjscheckboxradio-button

Dynamically change container when clicking radiobutton


I would like to change dynamically container after clicking on a radiobutton. I know I can do it easily using a ng-model and value. Here is a JSFiddle: http://jsfiddle.net/vDTRp/2/ It works fine when you have a small container or just some text. But how can I do that with a huge container stored in a scope ?

function MyCtrl($scope) {
    $scope.value[0]='<div>big container when clicking radiobutton 1</div>'
    $scope.value[1]='<div>big container when clicking radiobutton 2</div>'
    $scope.value[2]='<div>big container when clicking radiobutton 3</div>'
}

$scope.value[0] got the container of my radiobutton 1, $scope.value[1] got the container of my radiobutton 2 and $scope.value[2] got the container of my radiobutton 3.

What should the HTML be to do that dynamically ? (By 'dynamically' I mean clicking on a radiobutton changes the container as the example shown in the jsfiddle.)

Thank you a lot !


Solution

  • var myApp = angular.module('myApp',[]);
    
    function MyCtrl($scope) {
        $scope.number = '0';
        $scope.value = [];
      	$scope.value[0]='<div>big container when clicking radiobutton 1</div>';
        $scope.value[1]='<div>big container when clicking radiobutton 2</div>';
        $scope.value[2]='<div>big container when clicking radiobutton 3</div>';
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <div ng-app="myApp">
    <div ng-controller="MyCtrl">
    <input type="radio" ng-model="number" value="0">
    <input type="radio" ng-model="number" value="1">
    <input type="radio" ng-model="number" value="2">    
    <hr> 
    {{value[number]}}
    </div>
    </div>

    You can do with hide show container on selected radioButton like this

    <div ng-controller="MyCtrl">
        <input type="radio" ng-model="number" value="0">
        <input type="radio" ng-model="number" value="1">
        <input type="radio" ng-model="number" value="2">    
        <hr> 
        {{value[number]}}
        <div ng-bind-html-unsafe="value[number]"></div> <--if you want bind html than use ng-bind-html-unsafe
    </div>
    

    And change your controller like this

    function MyCtrl($scope) {
        $scope.number = '0';
        $scope.value = [];
        $scope.value[0]='<div>big container when clicking radiobutton 1</div>'
        $scope.value[1]='<div>big container when clicking radiobutton 2</div>'
        $scope.value[2]='<div>big container when clicking radiobutton 3</div>'
        $scope.$watch('value', function(value) {
           console.log(value);
        });
    }