我试图创建一个简单的
twitter bootstrap button group,允许用户选择几个选项之一(思考单选按钮).我有一个这样的一个点,它影响到模型的变化,但是“活动”状态没有被正确设置,除非我再次点击它?
I’ve created a fiddle和基本标记如下
<div range="justified" model="myModel" options="rangeOptions"></div> <hr/> <div range="vertical" model="myModel" options="rangeOptions"></div> <hr/> <pre>myModel:{{myModel}}</pre> <script type="text/ng-template" id="range.tpl.html"> <div class="btn-group btn-group-{{type}}" data-toggle="buttons"> <span class="btn btn-lg btn-primary" ng-repeat="option in options" ng-class="{active:option.id==model.range_id}" <!-- not working?? --> ng-click="activate(option.id)">{{option.label}}</span> </div> </script>
function Main($scope) { $scope.rangeOptions = [ {id:1,label:"Agree"},{id:2,label:"Neutral"},{id:3,label:"Disagree"} ]; $scope.myModel = {range_id: 2}; } angular .module('range',[]) .directive('range',function () { return { replace: true,scope: { type:'@range',model:'=',options:'=' },templateUrl:'range.tpl.html',controller: function ($scope,$element,$attrs) { $scope.activate = function (option) { $event.preventDefault(); }; } }; });
解决方法
你不需要90%的引导js来获得这样的东西,所有你需要做的就是做一个按钮组,并附加一些ng点击它和ng类:
function myscope($scope) { $scope.button = 'red'; } <div class="btn-group"> <a href="javascript:void(0)" ng-click="button = 'red'" ng-class="{ 'active' : button == 'red' }" class="btn">red</a> <a href="javascript:void(0)" ng-click="button = 'blue'" ng-class="{ 'active' : button == 'blue' }" class="btn">blue</a> <a href="javascript:void(0)" ng-click="button = 'green'" ng-class="{ 'active' : button == 'green' }" class="btn">green</a> </div>