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>
건배!
selected라고 하는 범위 속성을 만듭니다.인덱스 및 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>
가장 좋은 해결책은 디렉티브를 사용하는 것으로 보입니다.컨트롤러가 뷰가 갱신되고 있음을 알 필요는 없습니다.
Javascript:
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를 사용하여 활성화되도록 설정됩니다.
디렉티브를 사용하는 이유는 컨트롤러에 의존하지 않기 때문입니다.실제로 컨트롤러를 전혀 가지고 있지 않습니다("모델"이라는 이름의 변수를 뷰에 정의합니다).그런 다음 이 지시사항을 한 컨트롤러뿐만 아니라 프로젝트 내 어디에서나 재사용할 수 있습니다.
일반적으로 Angular에서는 ngRepeat 지시어를 사용하여 이러한 스팬을 출력합니다.또한 각 항목에는 ID가 있습니다.이것이 모든 상황에서 해당되는 것은 아니지만, 백엔드에서 데이터를 요구하는 경우에는 일반적으로 어레이 내의 오브젝트에 고유 식별자가 있는 경향이 있습니다.
이 ID를 사용하여 목록의 항목에서 클래스를 쉽게 전환할 수 있습니다(아래의 plunkr 또는 코드 참조).
오브젝트 ID를 사용하면 (다른 답변에 기재되어 있는) $index가 Angular로 정렬되어 엉망이 되었을 때 바람직하지 않은 영향을 제거할 수도 있습니다.
예: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(person.id 가 $scope.active Class 와 같으면 .active-disclass 를 적용합니다.이 클래스는 사용자가 항목을 클릭했을 때 설정됩니다.
이것이 누군가에게 도움이 되기를 바랍니다, 저는 ng-class의 표현이 매우 유용하다는 것을 발견했습니다!
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;
}
클래스만 변경/삭제합니다.
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
HTML
<span ng-class="{'item-text-wrap':viewMore}" ng-click="viewMore= !viewMore"></span>
언급URL : https://stackoverflow.com/questions/17928487/angular-js-how-to-change-an-elements-css-class-on-click-and-to-remove-all-others
'programing' 카테고리의 다른 글
도커 컨테이너의 디렉토리를 호스트에 마운트하는 방법 (0) | 2023.03.31 |
---|---|
잭슨 JSON에서 JSON을 검증하는 방법 (0) | 2023.03.31 |
FormData 추가가 작동하지 않습니다. (0) | 2023.03.31 |
Woocommerce 숍 페이지에서 제품 변형 이미지 가져오기 (0) | 2023.03.31 |
JSON 엔트리를 루프오버하려면 어떻게 해야 하나요? (0) | 2023.03.31 |