I am building an application with ng-webworker , i built a sample application with ng-webworker and added all the necessary javascript.But it does not work.
I need the function to be executed on the button click.
Code:
<md-button ng-click="callworker()">
CALL WEBWORKER
</md-button>
JS:
var routerApp =angular.module('DiginRt', ['ngMaterial','ngWebworker'])
routerApp.controller('AppCtrl', ['$scope',function($scope,Webworker) {
function doubler(num) {
return num * 2;
}
var myWorker = Webworker.create(doubler);
$scope.callworker = function() {
myWorker.run($scope.value).then(function(result) {
alert("Answer: " + result);
});
}
Here is the application
As per your new code link, $scope.value is not defined, you have to define it in your $scope;
var routerApp = angular.module('DiginRt', ['ngMaterial', 'ngWebworker'])
routerApp.controller('AppCtrl', ['$scope', 'Webworker', function ($scope, Webworker) {
$scope.value = 10; //Added this.
function doubler(num) {
return num * 2;
}
var myWorker = Webworker.create(doubler);
$scope.callworker = function () {
myWorker.run($scope.value).then(function (result) {
alert("Answer: " + result);
});
};
}]);
Related
This's my service. I've got variable isPolygonDrawingEnded there.
angular
.module('gillie.clients.app')
.service('mapDrawingService', mapDrawingService);
mapDrawingService.$inject = ['$ngBootbox', '$translate', 'fitPolygonService', 'mapCommonService'];
function mapDrawingService($ngBootbox, $translate, fitPolygonService, mapCommonService) {
var self = this;
var map;
var polygonFeatures;
var stopDrawingAction;
var isPolygonDrawingEnded = false;
var isDrawingMode = true;
self.startNewPolygonDrawing = function (afterDrowed) {
fitPolygonService.suggestPoint(isDrawingMode);
var modify = createModifyInteractionToPolygonFeatures();
var draw = createDrawInteraction();
attachDrawEvents(draw, afterDrowed);
map.addInteraction(draw);
stopDrawingAction = function() {
map.removeInteraction(draw);
map.removeInteraction(modify);
};
};
var attachDrawEvents = function (draw, afterDrowed) {
draw.on('drawend', function (e) {
e.preventDefault();
afterDrowed();
isPolygonDrawingEnded = true;
if (fitPolygonService.isPolygonsExist()) {
var geometry = e.feature.getGeometry();
e.feature.setGeometry(fitPolygonService.fitPolygon(geometry));
}
});
}
This is my controller. Here I need to change $scope.showCountButton when mapDrawingService.isPolygonDrawingEnded == true. So how can I know that value in service is changed ?
angular
.module('gillie.clients.app')
.controller('regionController', regionController);
regionController.$inject = ['$q', '$filter', '$scope', '$ngBootbox', '$translate', 'regionService', 'mapService', 'mapDrawingService', 'modalService', 'regionCommonService', 'alertService', 'nominatimCommonService', 'populationService', 'provinceCommonService', 'provinceService', 'rx'];
function regionController($q, $filter, $scope, $ngBootbox, $translate, regionService, mapService, mapDrawingService, modalService, regionCommonService, alertService, nominatimCommonService, populationService, provinceCommonService, provinceService, rx) {
$scope.showCountButton = false;
$scope.startRegionSelection = function (region) {
$scope.isSavingAvailable = true;
$scope.showCountButton = false;
if (currentEditingRegion && region && currentEditingRegion.Id === region.Id) {
return;
}
if(region)
mapService.clearRegion(region);
if (currentEditingRegion && !region) {
mapDrawingService.continuePolygonDrawing();
return;
}
if (region) {
mapDrawingService.stopPolygonDrawing();
mapDrawingService.clearMap();
currentEditingRegion = region;
mapDrawingService.startExistPolygonDrawing(region.Name, region.CoordinatesJson);
return;
}
mapDrawingService.startNewPolygonDrawing(function () {
$scope.showCountButton = true
});
};
When I use mapDrawingService.startNewPolygonDrawing function - the value of showCountButton changes but view doesn't. $scope.$apply produces this exception:
[$rootScope:inprog] $digest already in progress
When you are passing the callback function it is no longer in the scope of the controller which is why the view is not updating. You can use promises instead since you are asynchronous draw event.
Service
mapDrawingService.$inject = ['$q', '$ngBootbox', '$translate', 'fitPolygonService', 'mapCommonService'];
function mapDrawingService($q, $ngBootbox, $translate, fitPolygonService, mapCommonService) {
var self = this;
var map;
var polygonFeatures;
var stopDrawingAction;
var isPolygonDrawingEnded = false;
var isDrawingMode = true;
self.startNewPolygonDrawing = function() {
fitPolygonService.suggestPoint(isDrawingMode);
var modify = createModifyInteractionToPolygonFeatures();
var draw = createDrawInteraction();
var promiseObj = attachDrawEvents(draw);
map.addInteraction(draw);
stopDrawingAction = function() {
map.removeInteraction(draw);
map.removeInteraction(modify);
};
return promiseObj;
};
var attachDrawEvents = function(draw) {
return $q(function(resolve, reject) {
draw.on('drawend', function(e) {
e.preventDefault();
if (fitPolygonService.isPolygonsExist()) {
var geometry = e.feature.getGeometry();
e.feature.setGeometry(fitPolygonService.fitPolygon(geometry));
}
resolve();
});
});
}
Controller
mapDrawingService.startNewPolygonDrawing().then(function() {
$scope.showCountButton = true
});
I have this variable that is being controlled by the Factory and to update the Controller but it's not happening.
Here is what I have:
var app = angular.module('plunker', []);
app.controller('AppController', function($scope, AppFactory) {
var vm = this;
$scope.serverStatus = AppFactory.getStatus();
});
app.factory('AppFactory', function($timeout) {
var AppFactory = {};
var vm = this;
vm.serverStatus = true;
// Execute after 2 seconds of page start
$timeout(function() {
AppFactory.setStatus(false);
}, 2000);
AppFactory.setStatus = function(status) {
console.log('Server set to ' + status);
vm.serverStatus = status;
// Getting server status = false
AppFactory.getStatus();
};
AppFactory.getStatus = function() {
console.log('Getting server status: ' + vm.serverStatus);
return vm.serverStatus;
};
return AppFactory;
});
LIVE PLUNKER DEMO: https://plnkr.co/edit/62xGw7Klvbywp9TODWF4?p=preview
Do you think Directives would work better with 2-way-communication between a factory and controller?
Check this edited the plunkr https://plnkr.co/edit/z6tdr5?p=preview
var app = angular.module('plunker', []);
app.controller('AppController', function($scope,$timeout, AppFactory) {
var vm = this;
$timeout(function() {
AppFactory.setStatus(false);
$scope.serverStatus = AppFactory.getStatus();
}, 2000);
$scope.serverStatus = AppFactory.getStatus();
});
app.factory('AppFactory', function($timeout) {
var AppFactory = {};
var serverStatus = true;
// Execute after 2 seconds of page start
return {
getStatus: function () {
//console.log('Getting server status: ' + vm.serverStatus);
return serverStatus;
},
setStatus : function(status) {
var vm = this;
console.log('Server set to ' + status);
serverStatus = status;
// Getting server status = false
vm.getStatus();
}
};
});
Here's a solution that uses events, e.g.:
app.controller('AppController', function($scope, AppFactory) {
var vm = this;
$scope.$on('messageOne', function(event, data){
console.log(data);
$scope.serverStatus = data;
$scope.$apply(); //I think $apply() is not needed here!
});
$scope.serverStatus = AppFactory.getStatus();
});
app.factory('AppFactory', function($timeout, $rootScope) {
var AppFactory = {};
var vm = this;
vm.serverStatus = true;
// Execute after 2 seconds of page start
$timeout(function() {
AppFactory.setStatus(false);
}, 2000);
AppFactory.setStatus = function(status) {
console.log('Server set to ' + status);
vm.serverStatus = status;
// Getting server status = false
//AppFactory.getStatus();
$rootScope.$broadcast('messageOne', status);
};
AppFactory.getStatus = function() {
console.log('Getting server status: ' + vm.serverStatus);
return vm.serverStatus;
};
return AppFactory;
});
https://plnkr.co/edit/pARMnE3Wl0OeJezKuvLT?p=info
My JavaScipt code:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $compile) {
$scope.number=10;
$scope.init = function(i) {
var element = angular.element(document.querySelector('#play'));
var el = '<h1>{{number}}</h1>';
el += '<h1>'+i+'</h1>';
var generated = element.html(el);
$compile(generated.contents())($scope);
if(i==0) {
return false;
}
setTimeout($scope.init, 1000, i-1);
}
});
First time when the function init is called {{number}} It is shown as 10, but when the function init() is called again $cope.number appear as {{number}}. My question is: why $compile doesn't work well?
DEMO: http://plnkr.co/edit/ot2CNgUzZoZgIBsgMuCF?p=preview
Try this:
var app = angular.module("myApp", []);
app.controller("mtCtrl", function($scope, $compile, $timeout) {
$scope.number=10;
$scope.init = function(i) {
var element = angular.element(document.querySelector('#play'));
var el = '<h1>{{number}}</h1>';
el += '<h1>'+i+'</h1>';
var generated = element.html(el);
$compile(generated.contents())($scope);
if (i === 0) {
return false;
}
$timeout(function () {
$scope.init(i-1);
}, 1000);
};
$scope.init(10);
});
I'm looking on how to make a 60 seconds countdown using angular js.
I want to show the countdown on the page ! and when the countdown is finished, the controller should reload to execute the code again ! and get the update json object !
my controller looks like :
.controller('todaymatches', function($rootScope,$scope, $http) {
$http.get("http://www.domaine.com/updatedjson/")
.success(function (response) {
$scope.matches = response;
});
})
I'm made a code ! I'm not sure if this works properly ! anyway it's not working on my app.
$scope.countdown = function() {
stopped = $timeout(function() {
console.log($scope.counter);
$scope.counter--;
$scope.countdown();
}, 1000);
};
Here is a simple countdown example:
HTML
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>
<body>
<div ng-controller="CountdownController">
{{counter}}
</div>
</body>
</html>
Javascript
function CountdownController($scope,$timeout) {
$scope.counter = 60;
$scope.onTimeout = function(){
if ($scope.counter > 0) {
$scope.counter--;
mytimeout = $timeout($scope.onTimeout,1000);
} else {
$scope.counter = 60;
}
}
var mytimeout = $timeout($scope.onTimeout,1000);
}
Demo
'use strict';
var ngApp = angular.module('myApp', ['Test']);
var c1 = angular.module('Test', []);
c1.controller('Ctrl1', function ($scope, $timeout) {
$scope.coutDown = function () {
$scope.onTimeout = function () {
console.log("value", $scope.value);
$scope.value = $scope.value - 1;
return $scope.coutDown($scope.value);
};
var delay = $timeout($scope.onTimeout, 1000);
if ($scope.value < 1) {
$timeout.cancel(delay);
return true;
}
return false;
};
$scope.value = 5;
$scope.coutDown();
});
<div ng-app="myApp">
<div ng-controller="Ctrl1">
<h1>{{value}}</h1>
</div>
</div>
http://jsfiddle.net/pbxaD/49/
if you want to use $timeout you have to inject it. But why don't you just call the update method in a certain interval?
.controller('todaymatches', function($rootScope,$scope, $http, $interval) {
var update = function() {
$http.get("http://www.domaine.com/updatedjson/")
.success(function (response) {
$scope.matches = response;
});
};
var initialize = function() {
$interval(function() {
update();
}, 60 * 1000)
};
initialize();
})
I tried this for the count down and it seems to work.
app.controller('CountDownController', function($scope, $timeout) {
$scope.counter = 60;
$scope.countdown = function() {
if ($scope.counter === 0) {
// do your reload and execute here
//Just reset the counter if you just want it to count again
$scope.counter = 60;
return;
} else {
$timeout(function() {
console.log($scope.counter);
$scope.counter--;
$scope.countdown();
}, 1000);
}
};
$scope.countdown();
});
You could tie up the various things you want to do inside the if condition of the above code as commented. I just reset the counter after counting down to 0.
I coded the below directive for infinite scroll, my problem which I couldn't figure out why it just fire once when the directive is loaded, I need your advice on how to make my list infinite-scroll.
I'm using it to get data remotely and each time i'm calling it I add to the counter 25, so each time it would return more data.
Thanx,
angular.module('MyApp')
.controller('InboxCtrl', function($scope, InboxFactory) {
var counter = 0;
$scope.loadData = function() {
var promise = InboxFactory.getEvents(counter);
promise.then(function(result) {
$scope.events = result;
});
counter += 25;
};
});
angular.module('MyApp')
.factory('InboxFactory', function($http, $q) {
// Service logic
var defered = $q.defer();
function getUrl(count) {
return "api/inbox/get?request={'what':'Search','criteria':'inbox','criteriaId':null,'startTime':null,'endTime':null,'offset':" + count + ",'limit':25,'order':'event_time','direction':'DESC','source':''}";
}
function extract(result) {
return result.data.data;
}
// Public API here
return {
getEvents: function(count) {
$http.get(getUrl(count)).then(
function(result) {
defered.resolve(extract(result))
}, function(err) {
defered.reject(err);
}
);
return defered.promise;
}
};
});
angular.module('MyApp')
.directive('infiniteScroll', ['$timeout',
function(timeout) {
return {
link: function(scope, element, attr) {
var
lengthThreshold = attr.scrollThreshold || 50,
timeThreshold = attr.timeThreshold || 400,
handler = scope.$eval(attr.infiniteScroll),
promise = null,
lastRemaining = 9999;
lengthThreshold = parseInt(lengthThreshold, 10);
timeThreshold = parseInt(timeThreshold, 10);
if (!handler || !components.isFunction(handler)) {
handler = components.noop;
}
element.bind('scroll', function() {
var
remaining = element[0].scrollHeight - (element[0].clientHeight + element[0].scrollTop);
//if we have reached the threshold and we scroll down
if (remaining < lengthThreshold && (remaining - lastRemaining) < 0) {
//if there is already a timer running which has no expired yet we have to cancel it and restart the timer
if (promise !== null) {
timeout.cancel(promise);
}
promise = timeout(function() {
handler();
promise = null;
}, timeThreshold);
}
lastRemaining = remaining;
});
}
};
}
]);
<ul class="inbox-list" infinite-scroll="loadData()">
<li class="clearfix" ng-repeat="event in events">{{event}}</li>
</ul>
I Made some changes the more important is the use of ng-transclude and the creation of a new scope for the directive to pass the method and the parameters. You can have a look at the jsbind. Of course the data are hard coded so i could fake the behaviour.
<ul class="inbox-list" my-infinite-scroll composite-method="loadData()">