Let's say we have the following service:
myApp.factory('FooService', function () { ...
Then, from a controller, I would say:
myApp.controller('FooCtrl', ['$scope', 'FooService', function ($scope, FooService) { ...
The two-part question is:
Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller.
In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.
The Scope in AngularJS is the binding part between HTML (view) and JavaScript (controller) and it is a built-in object. It contains application data and objects. It is available for both the view and the controller. It is an object with available properties and methods. There are two types of scopes in Angular JS.
In Angular, the basic building block for communication with server is $http service. The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
Found a reasonable solution. Inject it into the bootstrap method (run), and add it to the root scope. From there it will be available to all controllers and views.
myApp.run(function ($rootScope, $location, $http, $timeout, FooService) { $rootScope.foo = FooService; ....
Re-reading the post I mentioned above, it didn't say "wrap" exactly... just "abstract", so I presume the poster was referring to this same solution.
For thoroughness, the answer to (1) is then:
myApp.controller('FooCtrl', ['$scope', function ($scope) { // scope inherits from root scope $scope.foo.doSomething(); ...
and the answer to (2) is simply:
{{doSomething()}}
Adding Christopher's comment to make sure it's seen:
@rob - According to best practices, the factory should be injected in to the controllers that need to use it, rather than on the root scope. As asked, question number one actually is the antipattern. If you need the factory 100 times, you inject it 100 times. It's barely any extra code when minified, and makes it very clear where the factory is used, and it makes it easier (and more obvious) to test those controllers with mocks, by having the required factories all listed in the function signature. – Christopher WJ Rueber Nov 25 '13 at 20:06
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With