我有一个像这样的 Controller ,它附加到 html 的 body
上。
angular.module("app", [])
.controller("MyCtrl", function($scope) {
// Here I perform some jquery code listening for click event
$("a").click(function() {
$(this).toggleClass("active");
});
});
现在,我想知道为什么这在 Controller 内部不起作用。我知道,如果我将其放入指令中,它就会起作用。
最佳答案
<强> Don't mix up JQuery with AngularJS ,因为这不是一个好的做法,
如果您想要一些切换功能,请使用内置 ngClick 由 AngularJs
提供的指令功能,而不是使用 JQuery
$("a").click
<强> Sample Demo 2
<强> Sample Demo 3
<强> Sample Demo 4
function MainController($scope) {
$scope.toggle = true;
}
.box {
color: white;
text-align: center;
height: 100px;
font-size: 86px;
}
.on {
background-color: green;
}
.off {
background-color: red;
}
.box-show-setup,
.box-hide-setup {
-webkit-transition: all linear 0.3s;
-moz-transition: all linear 0.3s;
-ms-transition: all linear 0.3s;
-o-transition: all linear 0.3s;
transition: all linear 0.3s;
}
.box-show-setup {
opacity: 0;
height: 0;
}
.box-show-setup.box-show-start {
opacity: 1;
height: 100px;
}
.box-hide-setup {
opacity: 1;
height: 0;
}
.box-hide-setup.box-hide-start {
opacity: 0;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MainController">
<button ng-click="toggle = !toggle">Toggle!</button>
<div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
<div class="box off" ng-hide="toggle" ng-animate="'box'">Off</div>
</div>
也请阅读这些美丽的东西
关于javascript - 为什么 dom 事件在 angularjs 的 Controller 内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969425/