I want a service which can share/auto sync data to 2 or more controllers like this example:
app.js (from example)
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
return { FirstName: '' };
});
myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.Data = Data;
});
Furthermore I need to load the data with ajax. I tried a bit but for ajax I need the promise (so the controller dont get changed data after init) which dont worked with the shared object like the fiddle link. If possible I want a solution without events (rootscope broadcast).
How can i use both techniques together? Do you guys know what I mean? :)
Change your service to like this:
myApp.factory('Data', function(){
this.name= { FirstName: '' };
return this;
});
Controllers:
myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.Data = Data.name;
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.Data = Data.name;
});
I tried a lot and now my code is:
angular.module("test").factory("TestFactory", ["$http", function TestFactory($http) {
var factory = {
data: [],
test: 123,
getData: function () {
$http.get("/blub.json").success(function (result) {
factory.data = [1,2,3];
});
},
addToData: function (newData) {
factory.data.push(newData);
}
};
factory.getData();
return factory;
}]);
angular.module("test").controller("TestControllerA", ["$scope", "TestFactory", function ($scope, TestFactory) {
$scope.factory = TestFactory;
}]);
angular.module("test").controller("TestControllerB", ["$scope", "TestFactory", function ($scope, TestFactory) {
$scope.factory = TestFactory;
setInterval(function () {
TestFactory.addToData(TestFactory.data.length + 1);
$scope.$apply(); //refresh view/html
}, 1000);
}]);
I there a "bad" part and can be performer or something?