Roland
Roland

Reputation: 9711

set a class on a div with ng-class on pageload

As in the title, I'm trying to set a class on a div on page load ( not on a click ) with angular ng-class but I have no clue how to or if it is possible. The div is wrapped in a module and controller where I was previously trying to set the variable with $scope.frontpage but it didn't work.

<div id="main" role="main" class="clearfix" data-ng-module="ValidationBoxModule" ng-controller="ValidationBoxClassController">
    <div validation-id="dataValidationSummary" validation-summary ng-class="frontpage" ></div>
    <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server"></asp:ContentPlaceHolder>
</div>

angular.module("ValidationBoxModule", []).controller("ValidationBoxClassController", ["$scope", function ($scope) {

    $scope.frontpage = "";

    ($("#main").find(".sliderBox")) ? $scope.frontpage = "frontpage" : $scope.frontpage = "";
}]);

So is there a way to do it ?

Upvotes: 1

Views: 2110

Answers (1)

Yoshi
Yoshi

Reputation: 54649

What you're trying to do is not the angular way. As in: "don't do DOM manipulation in the controller". Instead use a directive, e.g:

function Ctrl($scope) {
  $scope.frontpage = false;
}

angular.module('app', ['app.directives']);

angular.module('app.directives', []).directive('isFrontpage', function () {
  return {
    restrict: 'A',
    link: function (scope, element) {
      scope.frontpage = angular.element(element).find('#main .sliderBox').length > 0;
    }
  };
});

with:

<body ng-controller="Ctrl" is-frontpage>
  <div id="main">
    <div class="sliderBox"></div>
  </div>

  <div
    validation-id="dataValidationSummary"
    validation-summary
    ng-class="{frontpage: frontpage}">
  </div>
</body>

demo: http://jsbin.com/unihon/4/

Upvotes: 3

Related Questions