Get the value of a local variable into the controller in AngularJS - javascript

I have a JS file containing a controller and other functions structured like this:
class RandomCtrl {
constructor(randomService) {
this.randomService = randomService;
...
}
$onInit() {
getData.call(null, this);
}
...
}
function getData(RandomCtrl) {
...
}
function getChart(data) {
if (!data) {
return;
}
const chartOptions = getWeekHourlyOptions(data);
const allCols = [].concat(chartOptions.dataColumns);
allCols.push(["x"].concat(_.map(chartOptions.xAxis, element => moment(element).valueOf())));
const xVals = xAxisValues(chartOptions.xAxis);
...
}
...
RandomCtrl.$inject = ['randomService'];
export const Random = {
bindings: {
data: '<',
siteNames: '<'
},
templateUrl: randomPageHtml,
controller: RandomCtrl
};
I want to get the value of allCols from getChart() into the Controller.
I've tried to add it in $onInit like this.allCols = getData.allCols but it doesn't work. Probably not the right way.
Any solution to this?

Declare allCols as a global variable and populate the data in getChart()
send allCols in getChart() as return value so that whenever this method is called the return value can be stored into another variable and can be consumed

Related

Angularjs 1.6 Component : TypeError: Cannot set property 'detailsView' of undefined

.component.js class
export var breachDetailsConfig = {
template: template,
controller: BreachDetailsComponent
};
class BreachDetailsComponent extends AutoBoundDependencies {
static get $inject() { return ['breachDetailsService', '$http']};
constructor(...dependencies) {
super(dependencies);
}
$onInit(){
this.detailsView = [];
this.getBreachDetails().then(function(data){
this.detailsView = data; // getting error here
});
// this.getBreachDetails().then(function(detailsView) {
// this.detailsView = detailsView;
// }); // want to use this part
}
getBreachDetails() {
return this.$http.get('breach-mock.json').then((response) => {
console.log(response.data);
return response.data;
});
}
}
ADD:
getBreachDetails() {
// get the breach details from JSON
// this.breachDetailsService.getBreachDetails().then((detailsView) => {
// this.detailsView = detailsView;
// });
}
what wrong here - i am trying to make a service to get the data from http call I get an error TypeError:this.breachDetailsService.getBreachDetails is not a function
I have inject the service using following:
static get $inject() { return ['breachDetailsService', '$http']};
ADD:
restservice.js class
import angular from 'angular';
import breachDetailsService from './breach-details.service';
let restServiceModule = angular.module('rest-services', []);
restServiceModule.service('breachDetailsService', breachDetailsService);
This is all i have for configure, there is no controller js
export var breachDetailsConfig = {
template: template,
controller: BreachDetailsComponent
};
since you are using typescript, use arrow function(ES6 new feature) to keep the context.
this.getBreachDetails().then(data => { // <---- arrow function here
this.detailsView = data; // getting error here
});
or you can bind this manually
this.getBreachDetails().then(function(data){
this.detailsView = data; // getting error here
}.bind(this));

Angular2 : Bind view with callback variable

In my angular2 project, I read a csv file with FileReader. After the onloadend callback I have a variable which contain the content of my csv file.
Here my component.ts :
items: Array<any> = []
...
readCSV (event) {
let csvFileParseLog = this.csvFileParseLog;
r.onloadend = function(loadedEvt) {
devicesFile = files[0];
let csvFileParseLog = [];
parseDevicesCsvFile(contents) // One of my function which is an observable
.subscribe(newItems=> {
csvFileParseLog.push(newItems); // My result
},
exception => { ... }
);
};
}
I tried to bindcsvFileParseLog to my view by passing my value into items ... whithout success.
Here my componenet.html :
<div *ngFor="let c of csvFileParseLog">
{{ c.value }}
</div>
How can I display this content into my view component and loop on it with ngFor ?
r.onloadend = function(loadedEvt) {
should be
r.onloadend = (loadedEvt) => {
otherwise this won't work within that function.
and then just use
this.csvFileParseLog.push(newItems);
and just drop let csvFileParseLog = this.csvFileParseLog;
You also might need to inject
constructor(private cdRef:ChangeDetectorRef) {}
and call it in subscribe()
.subscribe(newItems=> {
this.csvFileParseLog.push(newItems);
this.cdRef.detectChanges();
},

Two-way databind on a forEach?

I have an object of products. The products i get from a resource (Product), store in a factory (productsStore), and iterate through in a controller.
In another controller, i want to either empty of refresh products via productsStore.empty(); or productsStore.get();. But either of them does nothing. Meaning my forEach, below, is not being run again, and the list not updated.
What am i doing wrong?
Controller:
vm.products = productsStore.get();
vm.products.$promise.then(function (data) {
angular.forEach(vm.products, function (child) {
//. some code
)};
)};
Factory:
myApp.factory('productsStore', function ($http, $q, Product) {
var products = "";
var get = function () {
return products = Product.query();
};
var empty = function () {
return products = {};
};
// Bind products
products = get();
return {
get: get,
empty: empty
};
});
Resource:
myApp.factory('Product', function ($resource) {
return $resource('http://api.com/api/products/:id', { id: '#id' }, {
update: {
method: 'PUT'
}
});
});
try to loop through the data you get after the promise is resolved, otherwise it's a rather useless variable.
angular.forEach(data, function(child) {
//...do something with the child
});
Also, you have a typo, that I'm not sure you have in your actual code. In your controller, end of block should be }) and not )}

How to access a variable inside an anguljarjs service from a function?

I have an angularjs service, that holds a model property for the frontend binding.
I also want to create a function that processes some input data and updates the model accordingly:
angular.module('test').service('testService', testService);
function testService() {
return {
model: [
mylist = null
],
setMyList: setMyList
};
function setMyList(data) {
//process data
mylist = data; //error: "model is not defined"
}
}
from any controller:
testService.setMyList(data);
Problem: the function cannot see the model. Why, and how could I change this?
I solved it as follows:
var model: {
mylist = null
};
return {
model: model,
setMyList: setMyList
}
function setMyList(data)...

Data flow issue with AngularJS

I have a function inside a directive that makes a query (and gets results, according to the console). The problem is that I can't seem to be able to store those results into a factory, and pass them to a controller.
This is the directive:
scope.getVersions = function(release) {
if (angular.isUndefined(release)) return;
musicInfoService.getReleaseVersions(release.id)
.success(function(data) {
dataService = data.versions;
console.log(dataService);
});
};
The console shows that dataService contains an array with the results.
Then, I try to store it into a factory:
app.factory('dataService', [function(){
return { items: [] };
}]);
And I call it in a controller:
function VersionController($scope, dataService) {
$scope.versions = dataService.items;
console.log($scope.versions);
}
But both items and $scope.versions come back an empty array. Did I miss something?
You should really use a backing field to store that data, and use setter and geter functions for writing and reading respectively:
app.factory('dataService', [function(){
var _items={};
return {
setItems:function(value){
_items=value;
},
getItems:function(){
return _items;
}
};
}]);
And for setting the data:
musicInfoService.getReleaseVersions(release.id)
.success(function(data) {
dataService.setItems(data.versions);
console.log(dataService);
});
and reading:
function VersionController($scope, dataService) {
$scope.versions = dataService.getItems();
console.log($scope.versions);
}
See demo plunk.
There's a misunderstanding of angular factories going on here. You're trying to set dataService = , which will never work.
As Mohammad mentioned, you need to have a variable set outside of your return value in the factory and the return value is basically an object with functions that allow you to manipulate your constant. So what you need is a getter "getItems()" for getting the items, and a setter "addItem(item)" for adding an item to your items array.
So you're never directly injecting your "items" into a controller, you're injecting a bunch of functions that can get or manipulate your "items".
scope.getVersions = function(release) {
if (angular.isUndefined(release)) return;
musicInfoService.getReleaseVersions(release.id)
.success(function(data) {
dataService.addItem(data.versions);
console.log(dataService.getItems());
});
};
app.factory('dataService', [function(){
var items = [];
return {
addItem: function(item) {
items.push(item);
},
getItems: function() {
return items;
}
};
}]);
function VersionController($scope, dataService) {
$scope.$watch(dataService.getItems, function(items) {
$scope.versions = items;
console.log($scope.versions);
});
}

Categories