<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>jqLite .css() setter/getter</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-init="model = {fontSize: 30}">
<div class="container">
<div class="row">
<div class="col-xs-6">
<h3>Change <code>font-size</code></h3>
<input id="chg-font-size" class="form-control" type="text" ng-model="model.fontSize">
</div>
<div class="col-xs-6">
<h3>Retrived <code>font-size</code></h3>
<pre><code>{{ model.getFontSize }}</code></pre>
</div>
</div>
<p class="result">
<span class="text-success" font-size-success="{{ model.fontSize }}">
<span get-font-size="model.getFontSize">Will change</span>
</span>
<span class="text-danger" font-size-error="{{ model.fontSize }}">Won't change</span>
</p>
</div>
</body>
</html>
var app = angular.module('myApp', []);
/**
* Create directives
* fontSizeSuccss, fontSizeError
*/
angular.forEach(['Success', 'Error'], function (suffix) {
var dirName = 'fontSize' + suffix;
app.directive(dirName, function () {
return {
restrict: 'A',
link: function(scope, iElm, iAttrs) {
iAttrs.$observe(dirName, function (val) {
val = parseInt(val, 10);
if (suffix === 'Success') {
// correct
iElm.css('font-size', val + 'px');
}
else if (suffix === 'Error') {
// wrong
iElm.css('font-size', val);
}
});
}
};
});
});
app.directive('getFontSize', function ($parse, $timeout) {
return {
restrict: 'A',
link: function(scope, iElm, iAttrs) {
var setter = $parse(iAttrs.getFontSize).assign,
getComputedFontSize = function ($elm) {
return $elm[0].ownerDocument.defaultView.getComputedStyle($elm[0]).fontSize;
};
scope.$watch(function (scope) {
return getComputedFontSize(iElm);
}, function (val) {
setter(scope, {
jqLite: iElm.css('font-size'),
computed: val
});
});
}
};
});
.result > span {
font-size: 24px;
}
#chg-font-size {
height: 39px;
}