AngularJS tips
Blogs20152015-07-15
ngClick: {$event: event}
ngClick directive (as well as all other event directives) creates $event variable which is available on same scope. This variable is a reference to JS event object and can be used to call stopPropagation():
<button ng-click="deleteUser(user.id,$index);$event.stopPropagation();">
<button ng-click="childHandler($event)">How do I call an Angular.js filter with multiple arguments?
//In templates, you can separate filter arguments by colons.
{{ yourExpression | yourFilter: arg1:arg2:... }}
//From Javascript, you call it as:
$filter('yourFilter')(arg1, arg2, ...);The link: orderBy filter doc
Showing Spinner GIF during $http request in angular
- Handles the click event
- Displays the spinner upon the start of the process
- Disables the button
- Calls the bound function for the event (returns a promise)
- Removes the spinner when done
- Enables the button
Clear $watch
$watch returns a deregistration function, calling it would deregister the $watcher.
var listener = $scope.$watch("quartz", function () {});
listener(); // would clear the watch
//or:
var unbindWatch = $scope.$watch("myvariable", function() {});
setTimeout(function() {
unbindWatch();
}, 1000);- All watchers will be removed when the scope is destroyed, you don’t need to manage those
- $scopes are not singletons in Angular, and they get created and destroyed when needed
- $scope.$on(‘$destroy‘, …);
directive scope: =, &, @
<div ng-controller="myController">
<div my-directive my-text="hello {{ bar }}" my-two-way-bind="foo" my-one-way-bind="bar">
</div>
</div>
angular.module("myApp", []).directive("myDirective", function () {
return {
restrict: "A",
scope: {
text: "@myText",
twoWayBind: "=myTwoWayBind",
oneWayBind: "&myOneWayBind"
}
};
}).controller("myController", function ($scope) {
$scope.foo = {name: "Umur"};
$scope.bar = "qwe";
});observe
observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src=“{{bar}}”). Not only is this very efficient but it’s also the only way to easily get the actual value because during the linking phase the interpolation hasn’t been evaluated yet and so the value is at this time set to undefined.
<input my-directive value="{{1+1}}">
app.directive('myDirective', function () {
return function (scope, element, attr) {
attr.$observe('value', function(actual_value) {
element.val("value = "+ actual_value);
})
}
});How to display length of filtered ng-repeat data
<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
$scope.$watch("query", function(query){
$scope.counted = $filter("filter")($scope.data, query).length;
});ui-bootstrap-tpls
ui-bootstrap-tpls.min.js == (ui-bootstrap.min.js + html templates) required by the js. If you only included ui-bootstrap.min.js, you will also need to provide your own html templates.
Others
$scope.persons.splice( $scope.persons.indexOf(person), 1 );