I currently have 2 javascript controllers: selectAll and listAllDomains.
I'm trying to call the method getBeanName (defined in listAllDomains) in the controller selectAll under:
response = $http.post('/invoke/selectAll/', INSERT_CALL_HERE);
As a note, the object returned by the method getBeanName will be passed as an argument to the $http.post() method and handled by a Java controller.
app.controller('listAllDomains', ['$http', '$scope', '$rootScope', function ($http, $scope, $rootScope) {
$scope.showSpinner = true;
$scope.showBtn = false;
let dataObj;
$http.get('domains/').then(function (response) {
$scope.showSpinner = false;
$scope.domains = response.data;
});
$scope.showButton = function(eleStatus) {
let eleSize = Object.keys(eleStatus).length;
return !eleSize;
};
$scope.getBeanName = function (objectType, objectName) {
dataObj = {
type : objectType,
name : objectName,
methodName : "select",
methodParameters : ["true"]
};
localStorage.setItem("dataObj", dataObj);
console.log(dataObj);
$rootScope.$emit("invokeSelectAll", dataObj);
return dataObj;
}
}]);
app.controller('selectAll', ['$http', '$scope' , '$rootScope',
function ($http, $scope, $rootScope) {
var response;
$rootScope.$on("invokeSelectAll", function(){
$scope.invokeSelectAll();
});
$scope.invokeSelectAll = function(){
console.log(localStorage.getItem("dataObj"));
response = $http.post('/invoke/selectAll/', INSERT_CALL_HERE);
response.success(function(data, status, headers, config) {
$scope.responses = data ? data : "Select Operation not supported on this bean";
});
}
}]);
Any help would be much appreciated! Thank you!
You can either create a service and inject it in both controllers or just define your function in $rootScope and then use it in any controller.
Check this issue for reference: How to use $rootScope in AngularJS
first create a service/factory with required function. And inject into the controller.
Related
im using angularJS v 1.5.6 and want to know how to pass my form data correctly with $location.path.
Here is my code Page A:
<form>
...
<button type="submit" ng-click="submit(formData)">submit</button>
</form>
JS:
app.config(['$routeProvider', function ($routeProvider) {$routeProvider
// Home
.when("/", {
templateUrl: "A.html",
controller: "ACtrl"
})
.when("/B/", {
templateUrl: "B.html",
controller: "BCtrl"
})
//fallback url if nothing matches
.otherwise({
redirectTo: '/'
});
}]);
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
$location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {
$scope.formData = $routeParams.formData;
}]);
it is a pretty simple example, but i cant figure out how to solve it :(
By clicking the submit nothing happens. If i remove the $scope from $scope.formData i get a error like: Error: formData is not defined.
The terms in formdata are available, i tested it with console.log($scope.formData) and everything is ok.
here is the link plunker: https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o
EDIT
the only issue is now, how to handle the select object correctly in the foreach loop. Need help please
You can do it by creating a service and using setter/getter in order to transfer a variable.
For example like this: https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview
app.service('TransferService', [function(){
var savedData,
service = {
getData: getData,
setData: setData
}
function getData(){
return savedData
}
function setData(data){
savedData = data
}
return service
}])
Don't use location.path...
You could either use a service or use localstorage (or some other browser storage mechanism [sessionStorage, indexdb].
Service Method Below
app.service("SomeService", function () {
var value = null;
this.set = function (val) {
value = val;
return this;
}
this.get = function () {
return value;
}
})
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
SomeService.set($scope.formData);
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
//Check that the data is present in the SomeService service.
var dataFromACtrl = SomeService.get();
if (dataFromACtrl) {
$scope.formData = dataFromACtrl;
}
})();
})
Using localStrorage below, could be sessionStorage.
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
window.localStorage.setItem("form_data", JSON.stringify($scope.form_data));
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
var dataFromACtrl = window.localStorage.getItem("form_data");
if (dataFromACtrl) {
$scope.formData = JSON.parse(dataFromACtrl);
}
})();
})
Note
Using the localStorage example you would need to do some clean-up, after doing whatever you want to do with that data in Bctrl you'd want to clear the entry in localstorage using either of the below lines of code:
window.localStorage.removeItem("form_data");
delete window.localStorage["form_data"];
I'm an angular newby. I'm hoping to pass params to a service that fetches data form a server depending on those params.
for example, if I want to pass a book name string and then use it in the service to concatenate with the request url. The documentation does not show clearly in this subject and I could not find helpful examples in other resources.
Let say, this is the controller:
app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books) {
// sending params to books service before a successful return
books.success(function(data) {
$scope.book = data[$routeParams.bookId];
});
and this is the service
app.factory('books', ['$http', function($http) {
// var url = 'http://...' + ParamFromController + '.json'
return $http.get(url)
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
So, how can I send params to 'books' service and then use it in the service?
Thanks a lot in advance.
You can declare your service as:
app.factory('books', ['$http', function($http) {
// var url = 'http://...' + ParamFromController + '.json'
return {
getVal: function(url,options){
return $http.get(url,options)
}
}
}]);
and use it in your controller and provide appropriate params to pass into 'books' service:
app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books) {
// sending params to books service before a successful return
books.getVal('api/activity.json',{'name':'abc'}).success(function(data) {
$scope.book = data[$routeParams.bookId];
});
Also, dont use the .success() callback both in your service and controller function. The books service is returning a promise($http returns a promise implicitly) and you can handle that in controller.
Right now you are returning the promise / result of the $http as the service instance.
Services are not meant to work this way. You should return an object that holds several properties / methods that define your service:
app.factory('books', ['$http', function($http) {
var instance = {
getBook: function(bookId) {
return $http.get(...);
}
}
return instance;
}
In the controller you can then use the books service as follows:
books
.getBook($routeParams.bookId)
.then(function (result) { ... });
app.factory('books', ['$http', function($http) {
var booksService = {};
booksService.getBook = function(bookId){
{
return $http.get(url, bookId);
};
return booksService;
}]);
and in your controller
app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books) {
books.getBook($routeParams.bookId).success(function(data) {
$scope.book = data;
});
I am trying to create an Angular Factory, this is based on a example from a plural site course http://www.pluralsight.com/training/player?author=shawn-wildermuth&name=site-building-m7&mode=live&clip=3&course=site-building-bootstrap-angularjs-ef-azure.
From debugging the code in Chrome it appears to run fine. I can see when I debug it that the service gets my data and puts it in my array but when I look at the controller in either $scope.data or dataService.data the arrays are empty. I don't see any javascript errors. I'm not sure what I'm doing wrong, any suggestions. I'm using AngularJS v1.3.15.
module.factory("dataService", function($http,$routeParams,$q) {
var _data = [];
var _getData = function () {
var deferred = $q.defer();
$http.get("/api/v1/myAPI?mainType=" + $routeParams.mainType + "&subType=" + $routeParams.subType)
.then(function (result) {
angular.copy(result.data,_data);
deferred.resolve();
},
function () {
//Error
deferred.reject();
});
return deferred.promise;
};
return {
data: _data,
getData: _getData
};});
module.controller('dataController', ['$scope', '$http', '$routeParams', 'dataService',function ($scope, $http, $routeParams, dataService) {
$scope.data = dataService;
$scope.dataReturned = true;
$scope.isBusy = true;
dataService.getData().then(function () {
if (dataService.data == 0)
$scope.dataReturned = false;
},
function () {
//Error
alert("could not load data");
})
.then(function () {
$scope.isBusy = false;
})}]);
On
return {
data: _data,
getData: _getData
};});
you have "data: _data," while your array is named just "data". Change the name of the variable to match and it will work:
var _data = [];
Why would you use deferred from $q this way?
The proper way to use $q:
$http.get("/api/v1/myAPI?mainType=" + $routeParams.mainType + "&subType=" + $routeParams.subType)
.success(function (result) {
deferred.resolve(result);
}).error(
function () {
//Error
deferred.reject();
});
And then in controller
dataService
.getData()
.then(function success(result) {
$scope.data = result; //assing retrived data to scope variable
},
function error() {
//Error
alert("could not load data");
});
In fact, there are some errors in your codes :
In your Service, you define var data = [];, but you return data: _data,. So you should correct the defination to var _data = []
you don't define _bling, but you use angular.copy(result.data,_bling);
One more question, why do you assigne the service to $scope.data : $scope.data = dataService ?
EDIT :
Notice that there 3 changes in the following codes:
comment the $scope.data = dataService;, because it makes no sense, and I think that $scope.data should be the data that the service returns.
$scope.data = dataService.data;, as I described in 1st point. You can see the result from the console.
In the if condition, I think that you want to compare the length of the returned data array, but not the data.
module.controller('dataController', ['$scope', '$http', '$routeParams', 'dataService',function ($scope, $http, $routeParams, dataService) {
// $scope.data = dataService;
$scope.dataReturned = true;
$scope.isBusy = true;
dataService.getData().then(function () {
if (dataService.data.length === 0){
$scope.dataReturned = false;
}else{
$scope.data = dataService.data;
console.log($scope.data);
}
},
// other codes...
})}]);
I am very new to angularjs and am having a hard time trying to figure out this issue.
Basically, we are using a factory to request data for our application. When the factory returns a promise, we were hoping that the data inside the returned promise that was defined in our scope, would be able to be used, but it is only returning as text on the page.
For example: We have defined $scope.name in our controller:
app.controller('AccountController',function($scope,Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().success(function(data) {
$scope.news.push(data);
});
});
so the factory (getSnapshot) will return something like "Hello {{name}}" from an $http request as follows:
app.factory('Account',function($http) {
return {
getSnapshot : function() {
return $http.get('data.php');
}
}
});
Is it possible to allow the factory to access /use {{name}} from the $scope?
You will need to use internal Angular $interpolate service:
app.controller('AccountController', function($scope, $interpolate, Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().success(function(data) {
var text = $interpolate(data)($scope);
$scope.news.push(text);
});
});
Use $q and promises thanks to #dfsq's answer on my post similar to this. Works perfectly.
Here's a plunker.
// Factory method.
app.factory('Account', function($http, $q) {
var data;
return {
getSnapshot: function() {
return data ? $q.when(data) : $http.get('data.json').then(function(response) {
data = response.data;
return data;
})
}
}
});
// Controller method.
app.controller('AccountController', function($scope, Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().then(function(data) {
$scope.news = data;
});
});
I have the following controller:
'use strict';
/* Controllers */
angular.module('stocks.controllers', []).
controller('MyCtrl1', ['$scope', '$http', 'stockData', function MyCtrl1 ($scope, $http, stockData) {
$scope.submit = function() {
$scope.info = stockData.query();
console.dir($scope.info);
}
}]);
and i want to pass a bound ng-model that sits in my view called ng-model="symbol_wanted" to the following service...
'use strict';
/* Services */
angular.module('stocks.services', ['ngResource']).factory('stockData', ['$resource',
function($resource){
return $resource('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', {}, {
query: {method:'GET', isArray:false}
});
}]);
how do i connect the controller's scope to get passed into the service? thanks!
how do i pass scope from controller to service in angularjs?
You can't inject $scope into services, there is no such thing as a Singleton $scope.
i want to pass a bound ng-model that sits in my view called ng-model="symbol_wanted" to the following service...
You can call the service and pass parameters this way:
.factory('stockData', ['$resource', '$q', function ($resource, $q) {
var factory = {
query: function (value) {
// here you can play with 'value'
var data = $resource('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', {}, {
query: {
method: 'GET',
isArray: false
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
So we call this service and get a promise back like this:
stockData.query(value) // <-- pass value
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
BTW, I'd suggest you use $http.get:
Demo Fiddle
Your ng-model value will automatically become a scope property. So, you can just use this in your controller to get the current value:
$scope.symbol_wanted;
So, let's say that you have a function to handle the click in your controller:
$scope.handleMyClick = function() {
stockData.query($scope.symbol_wanted);
}
You can just use the scoped property.