ocombe / ocModal

An angularJS modal directive & service
66 stars 16 forks source link

controller $scope #5

Closed morganwildermuth closed 10 years ago

morganwildermuth commented 10 years ago

Not sure if this is a bug, me misunderstanding a feature, or an implementation issue on my part, but if I set the controller of a modal to a controller that already exists and then within the modal call a method on ng-click then this method, if in the specified controller, will run but any changes to the $scope will not be reflected.

Example.

I set the modal controller to testCtrl. testCtrl already has $scope.testArray with 2 items in it and $scope.testDelete that removes the first item from the $scope.testArray. From the modal I call method testDelete on ng-click which also closes the modal. testDelete gets run, but the page behind the modal (which uses testCtrl and shows the values within $scope.testArray) does not reflect that deletion.

ocombe commented 10 years ago

Hi. It is not a bug (it's a feature!). You can use the same controller for different parts of your application, but the $scope injected by angular won't be the same, you will have 2 distinct instances of the controller.

In this case, your first controller is using a local $scope, and the controller in the modal is using a new scope that is generated for the modal only (and isolated scope).

If you want to share variables from another scope, you will need to use the init parameter when you open the modal. All init variables will extend the modal scope (and be in the $init parameter of the controller as well), it should then work as you expect.

You could also use $rootScope that is unique everywhere in your application because it is the root of all scopes.

morganwildermuth commented 10 years ago

Ah! I see; I was assuming that the purpose of referencing a ctrl was to connect to the scoped items within it, so I assumed it would not create a new instance of the controller. As for $init, that makes sense. I followed the outline in the ocModal documentation, but when I tried to inject the $init dependency into my controller I ran into an 'unknown provider' issue. For now I'm just relying on $rootScope, but thank you for the thorough explanation!