I am currently learning angular.js.
The following is an example I came up with. The goal:
- An editor for a dict, the dict format is: {key: [type, data]}
- A view of the same data
- The "type" should be validated. I use two types: "string" (can be anything) and "greeting" (a string that starts with hello)
- Don't care for minify compatibility
The first solution I came up with did the validation inside the controllor of the editor view - but I would prefer it to be global. Every time the global data changes - no matter from where - the validation should be run.
<!doctype html>
<html lang="en">
<head>
<script src="angular.js"></script>
<script>
'use strict';
var testApp = angular.module('testApp', []);
testApp.factory('Data', function ($rootScope) {
$rootScope.data = {'A String': ['string', 'Hello Foo'], 'A Greeting': ['Greeting', 'Hello Bar']};
$rootScope.validation = {};
// validate data.
$rootScope.$watch('data', function (newValue, oldValue) {
for (var key in newValue) {
var value = newValue[key];
if (value[0] == 'string') {
$rootScope.validation[key] = true;
} else if (value[0] == 'Greeting') {
$rootScope.validation[key] = value[1].indexOf('Hello') == 0;
} else {
console.log('error');
}
}
}, true);
return $rootScope.data;
});
testApp.controller('dataViewCtrl', function ($scope, Data) {
// Data must be injected somewhere so the factory is run.
// So even though this function does nothing the "Data" argument
// must be somewhere. What better way is there to initialize global data?
// i might do
// $scope.data = Data;
// but is there actually a point of doing so?
});
testApp.controller('dataEditorCtrl', function () {
});
</script>
</head>
<body ng-app="testApp">
<h2>The Editor</h2>
<div ng-controller="dataEditorCtrl">
<table>
<tr ng-repeat="(key, value) in data">
<td>{{ key }}</td>
<td><input ng-model="value[1]"></td>
<td ng-if="validation[key]">ok</td>
<td ng-if="!validation[key]">NOK {{ !validation[key] }}</td>
</tr>
</table>
</div>
<h2>Some View</h2>
<div ng-controller="dataViewCtrl">
<table>
<tr ng-repeat="(key, value) in data">
<td>{{ key }}</td>
<td>{{ value[1] }}</td>
</tr>
</table>
</div>
</body>
</html>