我有一个像这样的控制器附加到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");
});
});
现在,我想知道为什么这在控制器内部不起作用。我知道,如果我把它变成指令那么它确实有效。
答案 0 :(得分:1)
Don't mix up JQuery with AngularJS ,因为它不是一个好的做法,
如果您想要一些切换功能,请使用AngularJs
提供的内置 ngClick 指令功能,而不是使用JQuery
$("a").click
<强> Sample Demo 2 强>
<强> Sample Demo 3 强>
<强> Sample Demo 4 强>
function MainController($scope) {
$scope.toggle = true;
}
&#13;
.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;
}
&#13;
<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>
&#13;
还阅读这些美丽的东西