使用ng-click在angularjs中从all和addclass中删除所选内容

时间:2015-05-08 14:45:27

标签: jquery angularjs

当我单击文本时,我有事件div1例如将是粗体,并从另一个选中删除粗体,我尝试使用addClass但它没有用。我该如何解决这个问题? jsfiddle

HTML:

<div id='1_1' ng-click="addClassToSelected($event)">div1</div>
<div id='1_2' ng-click="addClassToSelected($event)">div1</div>
<div id='1_3' ng-click="addClassToSelected($event)">div1</div>
<div id='1_4' ng-click="addClassToSelected($event)">div1</div>
<div id='1_5' ng-click="addClassToSelected($event)">div1</div>
<div id='1_6' ng-click="addClassToSelected($event)">div1</div>
<div id='1_7' ng-click="addClassToSelected($event)">div1</div>

角:

$scope.addClassSelected = function(event){
            var id =event.target.id ;
            $('#'+id).addClass("bold-selected");
        };

CSS:

.bold-selected {
    font-weight: bold;
}

2 个答案:

答案 0 :(得分:0)

你真的应该读一下如何在使用角度时远离jquery。从这个主题开始:"Thinking in AngularJS" if I have a jQuery background?

这是你的问题的答案。首先,你的dom应该是这样的,如果它会重复的话:

<div 
    data-ng-class="{
        'bold-selected': option.id == selectedId
       }"
    data-ng-repeat="option in data" 
    data-ng-click="addClassToSelected(option.id)"
    id="1_{{ data.id }}">
    div1
</div>

其次,这就是你的控制器的样子:

function MyCtrl($scope) {
    $scope.data = [{ id: 1 },{ id: 2 },{ id: 3 },{ id: 4 },{ id: 5 },{ id: 6 },{ id: 7 }];
    $scope.selectedId = false;
    $scope.addClassToSelected = function(id){
        $scope.selectedId = id;
    }
}

这是最终版本的jsFiddle:http://jsfiddle.net/w2hfourg/

答案 1 :(得分:0)

jsfiddle答案

<span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
<span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>