Reputation: 11
I tought angular and faced with a problem: I have a SPA which contains two parts with controllers, the data returns from json file. The first conroller for showing the menu, the second - for adding a new item. For now in json file there are two object, but when I added a third item in the second controller, It dissapeared when I return on the first page. How can I fix it? I've read that factory can transfer the data between controllers, but I've never use It.
Angular module:
var myApp = angular.module("testModule", ['ngRoute']);
myApp.config(function ($routeProvider){
$routeProvider.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainCtrl'
})
.when('/add', {
templateUrl: 'pages/add.html',
controller: 'addCtrl'
})
})
myApp.controller("mainCtrl", function ($scope, $http) {
$http.get("model/data.json").success(function (response) {
$scope.list = response;
})
});
myApp.controller("addCtrl", function ($scope, $http) {
$scope.addAdv = function(newAdv){
$http.get("model/data.json").success(function (response) {
response.push({
name: newAdv.name,
shop: newAdv.shop
});
})
};
});
JSON file:
[{
"name": "New Item",
"shop": "Titan"
},
{
"name": "New Item1",
"shop": "Titan"
}]
Upvotes: 1
Views: 209
Reputation: 8176
This will work for you :
`
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"></button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
function sendData($scope) {
var arrayData = [1,2,3];
$scope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $http) {
$scope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>
`
Upvotes: 0
Reputation: 66
Upvotes: 0
Reputation: 51
As Daniel.v said, a service is the best way. There are also two less elegant alternatives:
But i mainly prefer services.
Upvotes: 0
Reputation: 2492
You can use angular services to share data between your controllers. you should first create service for getting information form your server
var app = angular.module('app', ['ngRoute']);
app.service('dataService', function($http) {
var data = {};
data.list = [];
var getData = function(){
$http.get("model/data.json").then(function (response) {
data.list = response.data;
},function(err){});
}
return {
getDataFromServer:getData,
getData:data,
}
});
Now you can use this service in your controller:
app.controller("mainCtrl", function ($scope, dataService) {
dataService.getDataFromServer();
});
app.controller("addCtrl", function ($scope, dataService) {
$scope.data = dataService.getData;
$scope.data.list.push({
name:"foo",
shop:"bar"
});
});
And here is jsfiddle code: https://jsfiddle.net/xqn5yu8g/
For more information about angular services take look at angularjs services document page
Upvotes: 1