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?

asked Aug 16, 2013 at 13:27
\$\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

answered Aug 28, 2013 at 11:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.