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>multiVariable values: {{multiVariable}}</h1>
<span>
# of values to hold <select ng-model="repeatTimes" ng-options="n for n in range"></select>
</span>
<ul>
<li ng-repeat="vary in multiVariable">
<span editable field="$index">{{vary}}</span>
</li>
</ul>
<br />
<form ng-submit="addElementToMultivar()">
<input type="text" ng-model="aNewElement" size="30" placeholder="add new element to multiVariable">
<input type="submit" value="add">
</form>
</div>
</div>
JavaScript
var $scope;
var app = angular.module('miniapp', []);
app.directive('editable', function() {
return {
restrict: 'A',
scope: {localIndex:'=field' },
template:
'<span>'+
'<input type="text" ng-model="multiVariable[localIndex]" ng-show="edit" ng-enter="edit=false"></input>'+
'<span ng-show="!edit" style="text-decoration:underline;">{{multiVariable[localIndex]}}</span>'+
'</span>',
link: function(scope, element, attrs) {
scope.edit = false;
scope.multiVariable = scope.$parent.$parent.multiVariable;
$(element).bind('click', function() {
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.multiVariable = ["Harry","William"];
$scope.range = [1,2,3,4,5,5,6,7,8,9];
$scope.repeatTimes = $scope.multiVariable.length;
$scope.$watch('repeatTimes', function(newVal, oldVal){
if(newVal > oldVal){//we don't really want to remove inserted elements?
$scope.multiVariable.length = newVal;
}
else{
$scope.repeatTimes = oldVal;
}
});
$scope.$watch('multiVariable.length', function(val){
//looking after array with holes
for(var i=0; i<$scope.multiVariable.length; i++){
if($scope.multiVariable[i] === undefined){
$scope.multiVariable[i] = 'default value';
}
}
});
$scope.addElementToMultivar = function() {
$scope.multiVariable.push($scope.aNewElement);
};
}