Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I wrote my very first directive and I'd like to get some suggestions for improvement. My code - plnkr.

webApp.controller('AppCtrl', function ($scope) {

$scope.expandAdd = function() {
    $scope.hiddenAdd = true;

};

$scope.addWeb = function() {
    $scope.hiddenAdd = false;
};


});


webApp.directive('enter',function(){
return {

    link: function (scope, element, attrs){

        scope.hiddenAdd = false;   //hides the site details at first
        //Invoke expender on the controller on mouse click
        element.bind('click', function(){
            console.log('clicked');
            scope.$apply(attrs.enter);
        });
    }
}
});

I have three points I think I can improve here but I'm not sure how:

  1. My directive is not modular enough, the line scope.hiddenAdd = false is bound to hiddenAdd. Is it possible to make it more flexible for future use? Though it seems two be picking to different bindings I think that is because they are both start with hidden.

  2. Inside the controller I'm doing DOM manipulation $scope.hiddenAdd = true; & $scope.hiddenAdd = false; from what I've read it all best be inside directives and I can't find the way to make it a pure directive.

  3. I read somewhere that it is not recommended to use $apply too often, is there a way to avoid using apply in my case?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Option 1: Don't use a directive.
What you are trying to do does not actually require a directive. It is simple enough to play with the scope.

  $scope.expandAdd = function() {
    $scope.hiddenAdd = true;
  };

  $scope.addWeb = function() {
    $scope.hiddenAdd = false;
  };

plnkr

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.