Search code examples
angularjsangularjs-scopeangular-directive

How to refactor directive and change functionality by checking parent scopes?


I have a form with a ton of duplicate functionality in 2 different Controllers, there are slight differences and some major ones in both.

The form sits at the top of a products view controller, but also inside of the products modal controller.

Test plunker: http://plnkr.co/edit/EIW6xoBzQpD26Wwqwwap?p=preview
^ how would you change the string in the console.log and the color of the button based on parent scope?

enter image description here

At first I was going to create a new Controller just for the form, but also the HTML was being duplicated, so decided to put that into a Directive, and just add the Controller code there.


My question now is this: How would I determine which parent scope the form-directive is currently being viewed in? Because depending on the parent scope the functions/methods behave differently.


So far I've come up with this:

.directive('productForm', function() {
    return {
        templateUrl: "views/products/productForm.html",
        restrict: "E",
        controller: function($scope) {
            console.log('controller for productForm');
            console.log($scope);
            console.log($scope.$parent);

            /*
              If parent scope is the page, then this...

              If parent scope is the modal then this instead...
            */
        }
    }
});

However it's giving me back $parent id's that look like 002 or 00p. Not very easy to put in if / else statements based on that information.

Have you guys run into this issue before?


Solution

  • You can define 'saveThis' in your controller and pass it to directive using '&'

      scope: {
          user: '=',
          saveThis : '&'
        },
    

    please see demo here http://plnkr.co/edit/sOY8XZtEXLORLmelWssS?p=preview That gives you more flexibility, in future if you want to use saveThis in another controller you can define it inside controller instead adding additional if statement to directive.