Collection of AngularJS snippets
ng-app ng-strict-di
angular.module('todoApp', [])
//dependencies in array .controller('TodoController', ['$scope', function($scope) { }]);
.controller('TodoController', ['$scope', function($scope) {
$scope.todos = [
{text:'Todo Item 1', done:true},
{text:'Todo Item 2', done:false}];
$scope.addTodo = function() {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.archive = function() {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) $scope.todos.push(todo);
});
};
}]);
(function () {
var root = $(document.getElementsByTagName('body'));
var watchers = [];
var f = function (element) {
if (element.data().hasOwnProperty('$scope')) {
angular.forEach(element.data().$scope.$$watchers, function (watcher) {
watchers.push(watcher);
});
}
angular.forEach(element.children(), function (childElement) {
f($(childElement));
});
};
f(root);
console.log(watchers.length);
})();
or via bookmarklet version and searching for ng-app on page
<a href="javascript:(function(){try{var a=$(document.querySelector('[ng-app], [data-ng-app]')),n=[],t=0,r=function(a){a.data().hasOwnProperty('$scope')&&angular.forEach(a.data().$scope.$$watchers,function(a){n.push(a)}),angular.forEach(a.children(),function(a){r($(a))})};r(a),t=n.length,alert(t+' watcher'+(t===1?'':'s')+'.')}catch(c){alert('This is not an Angular app.')}})();">WatchCount</a>
$http({method: 'GET', url: '/someUrl'})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
first way is prefered because it allows angular to capture, and handle exceptions and errors inside of its framework, second does not
//when we're inside callbacks that are outside of the Angular world,
//we need to explicitly tell angular to check the values
//for changes using $apply like this:
scope.$apply(function() {
..... // the code
});
//or you can do this:
... some code that changes the scope
scope.$apply();