[英]Jquery addClass doesn't seem to work in angularjs controller initialiser
I have the following HTML: 我有以下HTML:
<div data-ng-controller="CountdownCtrl" class="row countdown">
<div ng-repeat="event in events" class="hidden event col-sm-4">
...
In the controller for this, I'm trying to remove the hidden class on the event DIV: 为此,我正在尝试删除事件DIV上的隐藏类:
app.controller('CountdownCtrl', function($scope) {
...
$(".countdown .event").removeClass("hidden").addClass("Hello");
...
I've tried the JQuery bit outside of the controller as well, but It just doesn't seem to fire, I've tried adding in logging as well: 我也尝试过在控制器外部使用JQuery位,但是似乎并没有触发,我也尝试过添加日志记录:
$(".countdown .event").removeClass(function() { $log("Hello World"); return "hidden";}).addClass("Hello");
The Jquery pages and examples don't seem to indicate that I need any kind of iterator. jQuery页面和示例似乎并不表明我需要任何迭代器。
I even tried something close to their example: 我什至尝试了一些接近他们的例子:
$("p").removeClass(function() { $log("Hello World"); return "hidden";}).addClass("Hello");
but I go no logging and no paragraphs with the "Hello" class applied. 但我没有记录日志,也没有应用“ Hello”类的段落。
What am I doing wrong? 我究竟做错了什么?
Instead do this in directive
definition link function: 而是在
directive
定义链接函数中执行此操作:
app.directive('event', function (){
return {
restrict: 'C', // C for class directives
link: function (scope, el, attrs){
// do that here
$(el).removeClass("hidden").addClass("Hello");
}
}
});
Or another option is to use ng-class
such as : 或者另一个选择是使用
ng-class
例如:
<div ng-repeat="event in events" class="event col-sm-4" ng-class='{hidden: 2+2==4}'>
Here you can notice it should have some truthy condition to be added else it shouldn't. 在这里您可以注意到它应该有一些真实的条件要添加,否则就不应该添加。
Controller: 控制器:
app.controller('CountdownCtrl', function($scope) {
// default eventClass value
$scope.eventClass = 'hidden';
...
// your logic
$scope.eventClass = 'Hello';
...
Html: HTML:
<div data-ng-controller="CountdownCtrl" class="row countdown">
<div ng-repeat="event in events" class="{{eventClass}} event col-sm-4">
...
You just need to wait until all elements are loaded. 您只需要等待,直到所有元素都已加载。
One way is wrapping it with $(document).ready()
outside the controller code: 一种方法是在控制器代码外用
$(document).ready()
包装它:
$( document ).ready(function() {
$(".countdown .event").removeClass("hidden").addClass("Hello");
});
However, keep in mind that if you change the state without full page reload, the code won't run again. 但是,请记住,如果在不重新加载整个页面的情况下更改状态,则代码将不会再次运行。 In such a case, you need to handle the state change event and add the code there as well.
在这种情况下,您需要处理状态更改事件,并在其中添加代码。
尝试这个,
$(".countdown, .event").removeClass("hidden").addClass("Hello");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.