我想更改div
is clicked
的背景。那么,我如何以角度访问$(this)
div?
我的代码是:
<div id="single" ng-click="changeit()">
foobar
</div>
功能是:
$scope.changeit=function($scope){
// jquery code $(this).css({"background":"#A4A4A4"});
// how in angular ?
}
答案 0 :(得分:3)
您可以传递$event
并使用target
来检索当前点击的元素。
<div id="single" ng-click="changeit($event)">
asad
</div>
$scope.changeit = function ($event) {
$($event.target).css({ 'background': '#A4A4A4' });
}
使用指令方式,您可以这样做:
<div id="single" data-change-color>foobar</div>
changeColor
指令在元素上添加click
事件,并在点击时更改颜色。
(function () {
'use strict';
angular
.module('myModuleName')
.directive('changeColor', changeColor);
changeColor.$inject = [];
function changeColor () {
return {
restrict: 'A',
scope: {},
link: link
};
function link (scope, element) {
element.on('click', onClick(element));
}
function onClick (element) {
return function () {
element.css({ 'background': '#A4A4A4' });
}
}
}
}) ();
答案 1 :(得分:3)
在使用angular时,理想情况下DOM操作应该是指令的唯一域。这使我们不会将我们的控制器逻辑粘合到我们的DOM演示文稿中,这会造成可怕的混乱。考虑到这一点,Angular有两个与样式,ng-style和ng-class相关的指令。 Ng级如下所示。
https://docs.angularjs.org/api/ng/directive/ngStyle
https://docs.angularjs.org/api/ng/directive/ngClass
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<style>
.active{
background:red;
}
</style>
</head>
<body ng-controller="ctrl">
<button ng-click="activeButton = 1" ng-class="{'active' :activeButton==1}">Button 1</button>
<button ng-click="activeButton =2" ng-class="{'active' :activeButton==2}">Button 2</button>
<button ng-click="activeButton = 3" ng-class="{'active' :activeButton==3}">Button 3</button>
<script>
var app = angular.module("app",[]);
app.controller("ctrl",function(){});
angular.bootstrap(document,[app.name]);
</script>
</body>
</html>
&#13;