0

I have a function in my controller that manipulates the DOM. I understand this to be a bad practice and DOM manipulations should be moved into a directive. I'm having trouble pulling it out of the controller and into its own directive.

I have the following example code in my controller:

$scope.sidebarToggle = function() {
  if ($scope.request = null) {
    $(#container).switchClass('bottom', 'top', 400, 'linear');
    $scope.editing = true;
  }
  else {
    $(#container).switchClass('top', 'bottom', 400 'linear');
    $scope.editing = false;
  {
};

The above code's if conditions are very simplified, in the live code there are multiple conditions. Otherwise an ng-show/hide directive might have been possible.

The purpose of the code is to recognize the state the user is in, reveal/hide an off-screen sidebar (the class assignments), and set the 'editing' state of the controller.

How can this be refactored into a directive to accomplish the same goal?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Flignats
  • 1,234
  • 10
  • 21

3 Answers3

0

Take a look at the documentation for angular directives to get started. https://docs.angularjs.org/guide/directive

For 'angularising' the class of the container, use ng-class.

example @ Adding multiple class using ng-class

Community
  • 1
  • 1
Jay Jay Jay
  • 1,970
  • 2
  • 25
  • 47
  • Hi Jay - Thanks, I've definitely been reading through the docs and attempting to move the code, but have just been stuck on it. I often use the ng-class directive, but I believe the logic I have is too complex and/or fits better in a custom directive. – Flignats Sep 22 '15 at 18:39
  • Dont know if you absolutely need directives in this case. You could improve the above code just by moving the setting of the class to the angular markup and only setting the underlying angular scope variable in the controller. – Jay Jay Jay Sep 22 '15 at 18:43
0

You probably don't need to create your own directive for that.

Angular have already created some directives that could help you out.

In your case, you should use angular directive : ng-show and ng-class or ng-style

Exemple :

HTML

<div ng-show="request == null"> Edit </div>
<div ng-class="{'class-top': request == null,'class-bottom' : request != null}"> <div>

CSS :

.class-top{
...
}
.class-bottom{
...
}

Let me know if it works for you,

Nico

Nicolas2bert
  • 1,142
  • 7
  • 10
-1

Try this:

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {

    },
    link: sidebarToggle
  };
});

I think it's creating a directive and link to your function sidebarToggle

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
zif
  • 51
  • 6