Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs multiple controllers on one page

I have a page with multiple controllers, one of the controller is being used in 2 different divs within the same page. I am not sure if it is a scope issue or I just miss something in my code.

here is the plunkr http://plnkr.co/edit/IowesXE3ag6xOYfB6KrN?p=preview

I want to hide the textbox when the user clicks on 'Savings' link, display the box when clicking on 'Cost' link.

like image 371
Annie C Avatar asked Nov 26 '13 01:11

Annie C


People also ask

Can we have multiple controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application.

What is Ng controller in angular?

Definition and Usage. The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.

Why use AngularJS?

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.


2 Answers

Same controller, but declared twice. therefor - two scopes.
Normally the solution is to move the ng-controller declaration one dom level higher (in your case, to the body element. once only), and have it only once. Otherwise, look into angular services.

see updated plunkr: http://plnkr.co/edit/pWnx2mdMeOeH33LUeTGm?p=preview

like image 170
oori Avatar answered Sep 27 '22 20:09

oori


Every time you use ng-controller, you make a new instance of said controller, with it's own scope. If you set subCCtrl on the body tag (or a new parent), and remove it from the two divs it is currently on, it works for me.

Other solutions you might want to look in to are by keeping "hideThisBox" on the root scope, broadcasting an event when clicking on save or by keeping it in a service.

like image 32
kaesve Avatar answered Sep 27 '22 22:09

kaesve