Friday, 29 May 2015

Angular const vs value

//define module
var app = angular.module('app', []);
//define constant
app.constant("mynumberValue", 200);
//define value
app.value("numberValue", 100);
app.value("objectValue", { name: "dotnet-tricks.com", totalUsers: 120000 });
// only difference is that values cannot be used in module config function
app.config(function (mynumberValue) { //here value objects can't be injected
console.log("Before:" + mynumberValue);
mynumberValue = "New Angular Constant Service";
console.log("After:" + mynumberValue);
});
view raw constvsvalue hosted with ❤ by GitHub

Angular $evalAsync vs $timeout

$evalAsync runs within the digest cycle, before the watchers are processed, so will be performed earlier than if you use $timeout.

$evalAsync from a directive, should run after the DOM has been manipulated by Angular but before the browser renders.

$evalAsync from a controller, should run before the DOM has been manipulated by Angular (and before the browser renders) -- rarely do you want this.

$timeout, should run after the DOM has been manipulated by Angular and after the browser renders (which may cause flicker in some cases).

Angular $eval vs $parse

Both evaluate Angular expressions, the difference is $eval returns a result whereas $parse returns a function.

AngularJS $watch() vs $watchCollection()

Live demo
<!doctype html>
<html ng-app="Demo">
<head>
<title>Scope $watch() vs. $watchCollection() In AngularJS </title>
</head>
<style type="text/css">
a[ ng-click ] {
cursor: pointer;
text-decoration: underline;
}
</style>
<body ng-controller="AppController">
<h2>Scope $watch() vs. $watchCollection() In AngularJS</h2>
<h3>The collection:</h3>
<ul>
<li ng-repeat="item in collection">
id: {{ item.id }} timestamp: {{ item.value }}
</li>
</ul>
<p>
<a ng-click="changeShallowValue()">Add item to collection (shallow change)</a>
&mdash;
<a ng-click="changeDeepValue()">Change property on item (deep change)</a>
&mdash;
<a ng-click="rebuild()">Rebuild collection</a>
&mdash;
<a ng-click="clear()">Clear logs</a>
</p>
<h3>$watchCollection( collection ) Log</h3>
<ul>
<li ng-repeat="item in watchCollectionLog">{{ item }}</li>
</ul>
<h3>$watch( collection ) Log</h3>
<ul>
<li ng-repeat="item in watchLog">{{ item }}</li>
</ul>
<h3>$watch( collection, [ Equality = true ] ) Log</h3>
<ul>
<li ng-repeat="item in watchEqualityLog">{{ item }}</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular.min.js"></script>
<script type="text/javascript">
// Create an application module for our demo.
var app = angular.module("Demo", []);
app.controller(
"AppController",
function ($scope) {
// These are the log item to render upon change.
$scope.watchCollectionLog = [];
$scope.watchLog = [];
$scope.watchEqualityLog = [];
// I am the collection being watched.
$scope.collection = [
{
id: 1,
value: 0
}
];
// Use watchCollection().
$scope.$watchCollection(
"collection",
function (newValue, oldValue) {
addLogItem($scope.watchCollectionLog);
}
);
// Use watch() with default object equality,
// which defaults to use object REFERENCE checks.
$scope.$watch(
"collection",
function (newValue, oldValue) {
addLogItem($scope.watchLog);
}
);
// Use watch() method, but turn on deep object
// equality, which will compare the deep object tree
// for changes.
$scope.$watch(
"collection",
function (newValue, oldValue) {
addLogItem($scope.watchEqualityLog);
},
true // Object equality (not just reference).
);
// Change a deep value in an existing item on in the
// current collection.
$scope.changeDeepValue = function () {
// Add new item to collection.
$scope.collection[0].value = now();
};
// Add a new item to the collection, causing a change
// in the shallow topology of the collection.
$scope.changeShallowValue = function () {
// Add new item to collection.
$scope.collection.push({
id: ($scope.collection.length + 1),
value: now()
});
};
// I clear the log items.
$scope.clear = function () {
$scope.watchCollectionLog = [];
$scope.watchLog = [];
$scope.watchEqualityLog = [];
};
// I rebuild the underlying collection, completely
// changing the reference.
$scope.rebuild = function () {
$scope.collection = [{
id: 1,
value: 0
}];
};
// I add a log item to the beginning of the given log.
function addLogItem(log) {
var logItem = (
"Executed: " + now() +
" ( length: " + $scope.collection.length + " )"
);
log.splice(0, 0, logItem);
}
// I return the current UTC milliseconds.
function now() {
return ((new Date()).toUTCString());
}
}
);
</script>
</body>
</html>
view raw angular-watch hosted with ❤ by GitHub

Here is a comparison of the watch and watchCollection (default by ref) and watchCollection (by val equality). This code was based on a post from Ben Nadel's blog.


Angular with D3

Here is an example of using D3 inside an Angular application. Click here for live demo
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
'use strict';
var app = angular.module('app', []);
app.directive('ngSparkline', function () {
return {
restrict: 'A',
require: '^ngCity',
scope: {
ngCity: '@'
},
template: '<div class="sparkline">' +
'<input type="text" data-ng-model="ngCity">' +
'<button ng-click="showTemp()">Update</button>' +
'<div class="graph"></div>' +
'</div>',
controller: ['$scope', '$http', function ($scope, $http) {
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=imperial&cnt=7&callback=JSON_CALLBACK&q="
$scope.showTemp = function () {
$scope.getTemp($scope.ngCity);
};
$scope.getTemp = function (city) {
$http({
method: 'JSONP',
url: url + city
}).success(function (data) {
var weather = [];
angular.forEach(data.list, function (value) {
weather.push(value);
});
$scope.weather = weather;
});
}
}],
link: function (scope, iElement, iAttrs, ctrl) {
scope.getTemp(iAttrs.ngCity);
scope.$watch('weather', function (newVal) {
if (newVal) {
var highs = [];
angular.forEach(scope.weather, function (value) {
highs.push(value.temp.max);
});
chartGraph(iElement, highs, iAttrs);
}
});
}
}
});
var chartGraph = function (element, data, opts) {
var width = opts.width || 200,
height = opts.height || 80,
padding = opts.padding || 30;
//Remove svg element if it exists.
d3.select("svg").remove();
var svg = d3.select(element[0])
.append('svg:svg')
.attr('width', width)
.attr('height', height)
.attr('class', 'sparkline')
.append('g')
.attr('transform', 'translate(' + padding + ', ' + padding + ')');
svg.selectAll('*').remove();
var maxY = d3.max(data),
x = d3.scale.linear()
.domain([0, data.length])
.range([0, width]),
y = d3.scale.linear()
.domain([0, maxY])
.range([height, 0]),
yAxis = d3.svg.axis().scale(y)
.orient('left')
.ticks(5);
svg.append('g')
.attr('class', 'axis')
.call(yAxis);
var line = d3.svg.line()
.interpolate('linear')
.x(function (d, i) { return x(i); })
.y(function (d, i) { return y(d); }),
path = svg.append('svg:path')
.data([data])
.attr('d', line)
.attr('fill', 'none')
.attr('stroke-width', '1')
.attr('stroke', 'black');
}
app.directive('ngCity', function () {
return {
controller: function ($scope) {
}
}
});
</script>
<!-- my application styles -->
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
}
.ng-hide {
display: none !important;
}
</style>
</head>
<body ng-app="app">
<h2>Angular chart example</h2>
<div ng-sparkline ng-city="London" width='400'></div>
</body>
</html>
view raw angular-d3 hosted with ❤ by GitHub