Angular.js 클릭시 요소 CSS 클래스를 변경하고 다른 모든 요소를 제거하는 방법
두 요소를 토글하려고하므로 한 요소를 클릭하면 my-class의 모든 참조가 제거되고 자체에 적용됩니다. 어떤 아이디어?
<span id="1" ng-style="my-class" ng-click="tog=my-class"></span>
<span id="2" ng-style="my-class" ng-click="tog=my-class"></span>
건배!
selectedIndex라는 범위 속성과 itemClicked 함수를 만듭니다.
function MyController ($scope) {
$scope.collection = ["Item 1", "Item 2"];
$scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection
$scope.itemClicked = function ($index) {
$scope.selectedIndex = $index;
};
}
그러면 내 템플릿은 다음과 같습니다.
<div>
<span ng-repeat="item in collection"
ng-class="{ 'selected-class-name': $index == selectedIndex }"
ng-click="itemClicked($index)"> {{ item }} </span>
</div>
참고로 $ index는 ng-repeat 지시문 내에서 사용할 수있는 매직 변수입니다.
지시문 및 템플릿 내에서도 동일한 샘플을 사용할 수 있습니다.
다음은 작동하는 plnkr입니다.
http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview
http://jsfiddle.net/DotDotDot/zvLvg/ 와 같은 ng-class의 조건으로 시도해 보셨습니까 ?
<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>
나에게 가장 좋은 해결책은 지시문을 사용하는 것 같습니다. 컨트롤러가 뷰가 업데이트되고 있음을 알 필요가 없습니다.
자바 스크립트 :
var app = angular.module('app', ['directives']);
angular.module('directives', []).directive('toggleClass', function () {
var directiveDefinitionObject = {
restrict: 'A',
template: '<span ng-click="localFunction()" ng-class="selected" ng-transclude></span>',
replace: true,
scope: {
model: '='
},
transclude: true,
link: function (scope, element, attrs) {
scope.localFunction = function () {
scope.model.value = scope.$id;
};
scope.$watch('model.value', function () {
// Is this set to my scope?
if (scope.model.value === scope.$id) {
scope.selected = "active";
} else {
// nope
scope.selected = '';
}
});
}
};
return directiveDefinitionObject;
});
HTML :
<div ng-app="app" ng-init="model = { value: 'dsf'}"> <span>Click a span... then click another</span>
<br/>
<br/>
<span toggle-class model="model">span1</span>
<br/><span toggle-class model="model">span2</span>
<br/><span toggle-class model="model">span3</span>
CSS :
.active {
color:red;
}
나는 시연 하는 바이올린이 있습니다. 아이디어는 지시문을 클릭 할 때 변수를 현재 범위 ID로 설정하는 지시문에서 함수가 호출된다는 것입니다. 그런 다음 각 지시문도 동일한 값을 감시합니다. 범위 ID가 일치하면 현재 요소가 ng-class를 사용하여 활성화되도록 설정됩니다.
지시문을 사용하는 이유는 더 이상 컨트롤러에 의존하지 않기 때문입니다. 사실 저는 컨트롤러가 전혀 없습니다 ( "model"이라는 뷰에서 변수를 정의합니다). 그런 다음이 지시문을 하나의 컨트롤러뿐만 아니라 프로젝트의 모든 위치에서 재사용 할 수 있습니다.
Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.
You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).
Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.
Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.
Hope this helps someone, I've found expressions in ng-class to be very useful!
HTML
<ul>
<li ng-repeat="person in people"
data-ng-class="{'active-selection': person.id == activeClass}">
<a data-ng-click="selectPerson(person.id)">
{{person.name}}
</a>
</li>
</ul>
JS
app.controller('MainCtrl', function($scope) {
$scope.people = [{
id: "1",
name: "John",
}, {
id: "2",
name: "Lucy"
}, {
id: "3",
name: "Mark"
}, {
id: "4",
name: "Sam"
}];
$scope.selectPerson = function(id) {
$scope.activeClass = id;
console.log(id);
};
});
CSS:
.active-selection {
background-color: #eee;
}
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
HTML
<span ng-class="{'item-text-wrap':viewMore}" ng-click="viewMore= !viewMore"></span>
'Development Tip' 카테고리의 다른 글
Unix 쉘 스크립트에서 현재 날짜를 epoch로 가져옵니다. (0) | 2020.12.02 |
---|---|
ServletFilter의 ServletResponse에서 HTTP 상태 코드를 얻으려면 어떻게해야합니까? (0) | 2020.12.02 |
jQuery Uncaught TypeError : 정의되지 않은 'fn'속성 (익명 함수)을 읽을 수 없습니다. (0) | 2020.12.02 |
세분화 오류 : OS X에서 11 (0) | 2020.12.01 |
마이크로 데이터, RDFa 또는 JSON-LD 적절하거나 최상의 사용입니까? (0) | 2020.12.01 |