0

I have a state called homeInside and it's controller and template in my angularjs app (I'm using routing). There is a lot of elements, also a button with ng-click linked to doSomething. I have another state called homeOutside. This is completely is similar to first one, but doSomething do another task.

I don't want to duplicate anything. How can I do this with one single controller and template? Is it the reason that Angular2 components comes into play for such scenarios (with it's constructor)?

Any idea would highly appreciated.

Edit:

In the first state:

$scope.doSomething = function() { AuthService.logout(); } 

In the second one:

$scope.doSomething = function() { $state.go('dashboard'); } 

All of the other parts are exactly the same.

5
  • Could you show us you code? And do you want the answer about AngularJS or Angular2? Commented Apr 10, 2017 at 10:27
  • sounds like a directive that get a function injected Commented Apr 10, 2017 at 10:29
  • @Raulucco yes, but we are not sure, right? We need a snnipet. Commented Apr 10, 2017 at 10:31
  • @RaphaelParreira yes we need some example code, i just through the idea so he can think about it Commented Apr 10, 2017 at 10:33
  • Hey guys. Thanks for your responses. Please check edit part. Commented Apr 10, 2017 at 11:00

2 Answers 2

1

I would suggest creating a custom directive and passing in a function for doSomething

When creating the directive you use the '&' symbol to set a function as the directive parameter

Here is a good example that explain the usage https://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters

See the section where "add" is the function being passed in

Sign up to request clarification or add additional context in comments.

2 Comments

It seems directive is the only way. But still need to duplicate the template. Any way, thanks.
do not duplicate the template use transaclude so you can inject the changing part of the template and encapsulate the common thing of the template
0

In Angular v1.x You must make factory and inject it to you controllers where you want to make the same thing. If you need example of factory I give it to you.

1 Comment

Thanks. But I think this one doesn't relate to factory or service. Please see edit part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.