I have to share data between controllers. In this example I'm using an aside. This has the exact same functionality as a modal from Angular Bootstrap.
I put the aside in my service so I can close it from another controller.
The problem is that I have to share the complete scope / object in the service so i can share the data between the controllers. In my real example, there are many lists in this object so it seems like it's a bit of overkill if I put the complete object in my service.
Is there a better way to do this?
I have to change the value from the scope on my page (= input field) but also in the aside. But the aside must have a different controller. Or can I use the same controller (MainController
) for the aside? If I add the MainController
to the aside, it instantiate the MainController
again and the binding is lost. (See code example below)
AsideService.initAside($aside.open({
placement: 'right',
templateUrl: 'PropertiesSidebar.html',
size: 'lg',
controller: 'MainController'
}));
-
\$\begingroup\$ Welcome to Code Review! Your question can be better answered if you include a more substantial part of your code, as it's just one smaller file you can just include the whole of it. \$\endgroup\$ferada– ferada2014年12月03日 15:05:20 +00:00Commented Dec 3, 2014 at 15:05
-
\$\begingroup\$ I added a plunker link at the bottom of my question. There is all my code. \$\endgroup\$brammekuhh– brammekuhh2014年12月03日 15:10:54 +00:00Commented Dec 3, 2014 at 15:10
-
1\$\begingroup\$ Yes, however it's still policy here to include the full code to be reviewed, see e.g. this meta question. \$\endgroup\$ferada– ferada2014年12月03日 15:16:42 +00:00Commented Dec 3, 2014 at 15:16
1 Answer 1
I think you're on the right track. Having a model object owned by a service and referenced from multiple scopes is good practice. Having more references to the same object in this was isn't a cost you should worry about.
However the example could be improved with clearer layout and more meaningful naming. I would suggest something like the following style.
angular.module('asideApp', ['ui.bootstrap', 'ngAside'])
.service('AsideService', function ($timeout) {
var model = {
aside: null,
text: null
};
function initAside(aside) { shared.aside = aside; }
return {
model: model,
initAside: initAside
};
})
.controller('MainController', function ($scope, $aside, AsideService) {
$scope.shared = AsideService.model;
$scope.openAside = function () {
AsideService.initAside($aside.open({
placement: 'right',
templateUrl: 'PropertiesSidebar.html',
size: 'lg',
controller: 'AsideController'
}));
};
})
.controller('AsideController', function ($scope, AsideService) {
$scope.shared = AsideService.model;
});
Explore related questions
See similar questions with these tags.