单击radiobutton时动态更改容器

时间:2017-11-28 10:41:09

标签: javascript angularjs button checkbox radio

我想在点击radiobutton后动态更改容器。我知道我可以使用ng-model和value轻松完成。 这是一个JSFiddle: http://jsfiddle.net/vDTRp/2/ 当你有一个小容器或一些文本时,它工作正常。但是如何使用存储在范围内的巨大容器来做到这一点呢?

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]有我的单选按钮1,$ scope.value的容器[1]得到了我的单选按钮2的容器和$ scope.value [2]得到了我的单选按钮3的容器中。

HTML应该动态地做什么? (动态地&#39;我的意思是点击一个单选按钮会改变容器,就像jsfiddle中显示的那样。)

非常感谢你!

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
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>';
}
&#13;
<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>
&#13;
&#13;
&#13;

你可以在选定的radioButton上使用隐藏节目容器,就像这样

<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>

然后像这样改变你的控制器

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);
    });
}