1
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.