I am new to Angular and quite frankly Java Script in general. I have been building a prototype app from some examples and tutorials and have run into a presumably simple issue that can be solved by passing parameters.
I want to receive a parameter in my controller (myKey) and pass it along to the factory which in turn will pass it along to a web API. I can define a constant for myKey in the factory and have everything work, I am having an issue in passing a parameter along.
Sorry for the newbie question and yes I have more study to do.
Thanks
'use strict';
/* Factories */
angular.module("myApp.myViewer.factories", []).factory('myThings', ['$resource',
function ($resource) {
var resource = $resource('/api/myThings', {}, { get: { method: 'GET', params: { myKey:"M1234" } } });
return resource;
}
]);
/* Controllers */
angular.module("myApp.myViewer.controllers", [])
.controller('myCtrl', ['$scope', 'myThings', function ($scope, myThings) {
myThings.get(function (response) {
console.log(response);
$scope.myThing = response;
});
}]);
1 Answer 1
You have two separate modules there that know nothing about each other. You would have to add one module as a dependency of the other, so something like this:
angular.module("myApp.myViewer.controllers", ["myApp.myViewer.factories"])
But I think that would over complicate things in this case and I think you would be better of combining the two modules like this:
You also need to add ngResource as a dependency and make sure you have it loaded on your pages as it doesn't come with Angular.
angular
.module("myApp", ['ngResource'])
.factory('myThings', ['$resource', function ($resource) {
return {
// define a function that returns your $resource after
// passing in the 'myKey' parameter
resource: function(myKey){
return $resource('/api/myThings', {}, {
get: {
method: 'GET',
params: { myKey: myKey }
}
});
}
};
}
])
.controller('myCtrl', ['$scope', 'myThings', function ($scope, myThings) {
// inject the myThings service and call the resource function
// that we defined to create your resource object.
var Keys = myThings.resource(myKey)
// make a get request on your resource and
// assign the response value to a $scope variable
// so any properties on your response object can be displayed in
// your view template
Keys.get(function (response) {
console.log(response);
$scope.myThing = response;
});
}]);
ng-submitorng-modelcorrectly.