问题
Afternoon All,
We have been trying to learn AngularJS for the last week and need a little guidance on this, we want to be able to store data e.g userName, brandName and productName between routes. At the moment we are using routeParams but find this a pain having to duplicate code over and over.
Also within section (3) we have formData is they a way we can store this data within a factory so we can jump between brands and update products before submitting the final data? as at the moment when we leave each brand it removes our inputted data.
If anyone could help we'd greatly appreciate it, Thank you.
Plunker Example
var amlProductCtrl = angular.module('amlProductCtrl', []);
// (1) Employees
amlProductCtrl.controller('employees', ['$scope', '$http',
function($scope, $http) {
$http.get('json/employees.json').success(function(data) {
$scope.employees = data;
});
}
]);
// (2) Brands
amlProductCtrl.controller('brands', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
// UserName
$scope.employee = {"userName": $routeParams.userName};
// Welcome Message
$scope.alerts = [{
type: 'info',
msg: 'Hello ' + $scope.employee.userName + ', please select a brand.'
}];
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
// Get JSON Data
$http.get('json/brands.json').success(function(data) {
$scope.brands = data;
});
}
]);
// (3) Products
amlProductCtrl.controller('products', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
// BrandName
$scope.brand = {"brandName": $routeParams.brandName};
// UserName
$scope.employee = {"userName": $routeParams.userName};
// Get JSON Data
var rpBrandName = $routeParams.brandName; // BrandName
var rsBrandName = rpBrandName.replace(/\s+/g, ''); // Remove Space
var lcBrandName = rsBrandName.toLowerCase(); // Lowercase
var brandName = lcBrandName;
$http.get('json/'+brandName+'-products.json').success(function(data) {
$scope.products = data;
});
// FormData
$scope.formData = {};
}
]);
回答1:
Here's a posible solution. Make a service that share the data between controllers. It's using $watch so may not be the most eloquent solution. I'm learning as well so I can feel your pain :-)
myApp.factory('DataService', function () {
var myObject = {
id: 0, name: 'not set'
};
return {
brandName: function () {
return myObject.name;
},
setBrandName: function (brand) {
myObject.name = brand.name;
}
};
});
You can construct your object to better reflect your needs. Google this there are many articles providing solutions. Hope this helps. check this plunker out: http://plnkr.co/edit/9rw3kHCfwatqAw6TRQeW?p=preview Go to #2 and select a brand. You'll notice the other 2 updating to the selected item.
来源:https://stackoverflow.com/questions/26591837/angularjs-store-data-factory