Angular mini app
A mini app showing several aspects of angular, such as scope handling, directives, etc
by odiseo
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="miniapp">
<div ng-controller="Ctrl">
<h1>Selected values {{selectedOptions()}}</h1>
<ul>
<li ng-repeat="option in options">
<input type="checkbox" value="{{index}}" ng-model="option.checked" />
<span editable field="option.text">{{option.text}}</span>
</li>
</ul>
<br />
<form ng-submit="addOption()">
<input type="text" ng-model="optionText" size="30" placeholder="add new option here">
<input type="submit" value="add">
</form>
</div>
</div>
JavaScript
var $scope;
var app = angular.module('miniapp', []);
app.directive('editable', function() {
return {
restrict: 'A',
scope: {field: '='},
replace: false,
template:
'<span>'+
'<input type="text" ng-model="field" ng-show="edit" ng-enter="edit=false"></input>'+
'<span ng-show="!edit">{{field}}</span>'+
'</span>',
link: function(scope, element, attrs) {
scope.edit = false;
$(element).bind('click', function() {
console.log('clicked on '+scope.field);
scope.$apply(scope.edit = true);
});
}
};
});
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind('keypress', function(e) {
if (e.charCode === 13 || e.keyCode ===13 ) {
scope.$apply(attrs.ngEnter);
}
});
};
});
function Ctrl($scope) {
$scope.options = [
{text: "Aaa", checked: true},
{text: "Bbb", checked: true},
{text: "Ccc", checked: true}
];
$scope.selectedOptions = function() {
var selValues = [];
_.each($scope.options, function(option) {
if (option.checked) {
selValues.push(option.text);
}
});
return selValues;
};
$scope.addOption = function() {
$scope.options.push({
text: $scope.optionText,
checked: true
});
$scope.optionText = '';
};
}