How can I access a property of a controller in a service?
In my case it is an array, which I want to change in my service.
My controller:
myApp.controller('MainController', function ($scope, $interval, externalDataService, AnalyzeService) {
$scope.myArray = [];
var size = 10;
var analyze = function () {
if($scope.myArray .length > size) {
AnalyzeService.doSomething();
}
};
var analyzeData = function () {
externalDataService.getData().then(function (data) {
$scope.faceReaderData.push(data);
analyze();
});
};
$interval(analyzeData , 2000);
});
My service:
myApp.service('AnalyzeService', function () {
this.doSomething = function () {
//here i want array access
}
});
You do not want to do that, as it would make your service depend on your controller, which is very undesireable. Instead, add the array as a parameter to your doSomething
:
//Appending 1,2,3 to the given array
function doSomething(someArray) {
return someArray.concat(['1', '2', '3']);
}
This way, your service does not depend on your controller at all, seperating your business logic from your controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.