simple angular function explanation needed - javascript

I created a simple angular function. The purpose is to display a changing value of variable x after pressing a button which triger the function startAction. It is not working and I have no idea why.
var app = angular.module("myApp", []);
app.controller('myController', ($scope, fabryka) => {
$scope.startAction = function () {
setInterval(function () {
var x = 0;
$scope.x = (function () {
x++;
return x;
})();
}, 500);
}
});

Angular has its own setInterval wrapper: $interval.
This piece of code counts seconds as you press the button. Please note the interval cancellation when the scope is destroyed.
angular.module('app', [])
.controller('mainCtrl', function($scope, $interval) {
var vm = this;
vm.x = 0;
var interval;
vm.startAction = function() {
vm.isRunning = true;
interval = $interval(function() {
vm.x++;
}, 1000);
};
vm.stopAction = function() {
vm.isRunning = false;
$interval.cancel(interval);
}
$scope.$on('$destroy', vm.stopAction);
return this;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="mainCtrl as vm">
<div>x: {{vm.x}}</div>
<button ng-click="!vm.isRunning? vm.startAction():vm.stopAction()">{{vm.isRunning? 'Pause':'Start'}}</button>
</div>

Related

How to invoke a function(like playing a an audio which says "STOP") when the stopwatch passes over a minute in AngularJS?

var app = angular.module('fruitjs.timer', []);
app.controller('timerController', [ '$scope', '$interval', function($scope, $interval) {
var interval, incrementTimer, actions;
actions = { start: "Start", stop: "Stop" };
$scope.timer = 0;
$scope.action = actions.start;
incrementTimer = function() {
$scope.timer += 1;
};
$scope.toggle = function() {
if ($scope.action === actions.start) {
$scope.action = actions.stop;
interval = $interval(incrementTimer, 1000);
} else if ($scope.action === actions.stop) {
$scope.action = actions.start;
$interval.cancel(interval);
}
};
$scope.reset = function () {
$interval.cancel(interval);
$scope.timer = 0;
$scope.action = actions.start;
};
}]);

How can I call a function in an angular controller?

I have a angularJS file like this; I need to call the newGame function in the end of the controller not in html. Can anyone help me with this?
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.newGame = function () {
$scope.random = Math.floor(Math.random() * 100) + 1;
$scope.display = "Start guessing";
};
$scope.giveUp = function () {
$scope.display = $scope.random;
};
$scope.check = function () {
if ($scope.guess > $scope.random) {
$scope.display = "Guess Higher"
} else if ($scope.guess < $scope.random) {
$scope.display = "Guess Lower"
} else {
$scope.display = "You got it!"
}
};
});
It's a function just like any other function. Add $scope.newGame(); at the end of your controller.

How to get rid of jQuery accretions and improve my current directive in angular way?

I would like to have button or link with icon, default glyphicon-play or glyphicon-pause if interval is enabled. How can I refactor this directive especially $element.hasClass("glyphicon-pause") or $element.removeClass("glyphicon-pause").addClass("glyphicon-play"); in more "angular way"?
<button play class="btn glyphicon glyphicon-play"></button>
Current directive:
app.directive('play', ['$interval', function ($interval) {
return {
restrict: 'A',
link: function ($scope, $element, attrs) {
var i = 0,
interval;
var play = function () {
$interval.cancel(interval);
interval = $interval(function () {
$scope.states[i].active = false;
$scope.states[i++].active = true;
i = i % 3;
}, 1000);
};
var stop = function () {
$interval.cancel(interval);
};
console.log($element, attrs);
$element.on('click', function ($event) {
if ($element.hasClass("glyphicon-pause")) {
$element.removeClass("glyphicon-pause").addClass("glyphicon-play");
stop();
} else {
$element.removeClass("glyphicon-play").addClass("glyphicon-pause");
play();
}
});
}
};
}]);
Using ng-class and ng-click would be the two most angular-like improvements here.
<button play class="btn glyphicon" ng-class="{glyphicon-play: isPlaying, glyphicon-pause: !isPlaying}" ng-click="togglePlay()"></button>
app.directive('play', ['$interval', function ($interval) {
return {
restrict: 'A',
link: function ($scope, $element, attrs) {
$scope.isPlaying = false;
var i = 0,
interval;
var play = function () {
$scope.isPlaying = true;
$interval.cancel(interval);
interval = $interval(function () {
$scope.states[i].active = false;
$scope.states[i++].active = true;
i = i % 3;
}, 1000);
};
var stop = function () {
$scope.isPlaying = false;
$interval.cancel(interval);
};
console.log($element, attrs);
$scope.togglePlay = function() {
if($scope.isPlaying){
stop();
}else{
play();
}
};
}
};
}]);

Implementing a delay ($timeout) to a $http request with AngularJS

I have a particular function dependant on a (previously executed) service that will trigger multiple queries to a 3rd party API. This API with cancel the requests if it gets too many of them too quick. Is there a way to set a delay to the $http query?
Here is my $http code:
$scope.getImages = function (title, name) {
$http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json').
success(function(data4) {
$scope.images = data4;
});
}
EDIT Upon request I paste my whole JS (probably I should have done so from the start)
angular.module('myApp', ['ngResource'])
function Ctrl($scope, $http) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
}
}
$scope.$watch('name', search, true);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=10').
success(function(data2) {
$scope.releases = data2.releases;
});
$scope.clicked = true;
$scope.sliding = true;
}
$scope.getImages = function (title, name) {
$http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json').
success(function(data4) {
$scope.images = data4;
});
}
};
I assume you will want to debounce your calls somehow, something simple like this should work. It will make the call every 300ms unless search(name) is called again before it fires.
var debounce = null;
var search = function(name) {
$timeout.cancel(debounce);
if (name) {
debounce = $timeout(function() {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5')
.success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
},300);
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
}
}

Error in angular js controller for pagination

I am coding in angular js for client side pagination.
Starting in other question here about pagination, I've transformed the code to this but doesn't work.
What is wrong?
myapp.controller('MainCtrl', function($scope, Events) {
$scope.mydata = [];
Events.query(function(data) {
$scope.mydata = data;
});
$scope.get = function (offset, limit) {
return $scope.mydata.slice( offset, offset+limit );
};
$scope.count = function () {
return $scope.mydata.length;
};
$scope.numPerPage = 5;
$scope.noOfPages = Math.ceil($scope.count / $scope.numPerPage);
$scope.currentPage = 1;
$scope.setPage = function () {
$scope.data = $scope.get( ($scope.currentPage - 1) * $scope.numPerPage, $scope.numPerPage );
};
$scope.$watch( 'currentPage', $scope.setPage );
});
$scope.get and $scope.count don't work. Events.query is getting all JSON data from service in array format.
I can test this code in chrome angular js extension.
Any idea?
Use {{mydata.length}} in your html instead of the $scope.count function.

Categories

Resources