简体   繁体   中英

Jquery addClass doesn't seem to work in angularjs controller initialiser

I have the following 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:

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:

    $(".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.

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.

What am I doing wrong?

Instead do this in directive definition link function:

 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 :

   <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.

Is this working? You have forgotten an ,

$(".countdown,.event").removeClass("hidden").addClass("Hello");

$(".intro,.demo") All elements with the class "intro" or "demo"

see w3schools

Controller:

app.controller('CountdownCtrl', function($scope) {
  // default eventClass value
  $scope.eventClass = 'hidden';

  ...
  // your logic
  $scope.eventClass = 'Hello';
  ...

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(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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM