/** * The MIT License * * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function(window, document){ /** * * Base64 encode / decode * http://www.webtoolkit.info/ * **/ var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } };if (typeof document.getAttribute == 'undefined') document.getAttribute = function() {}; if (typeof Node == 'undefined') { Node = { ELEMENT_NODE : 1, ATTRIBUTE_NODE : 2, TEXT_NODE : 3, CDATA_SECTION_NODE : 4, ENTITY_REFERENCE_NODE : 5, ENTITY_NODE : 6, PROCESSING_INSTRUCTION_NODE : 7, COMMENT_NODE : 8, DOCUMENT_NODE : 9, DOCUMENT_TYPE_NODE : 10, DOCUMENT_FRAGMENT_NODE : 11, NOTATION_NODE : 12 }; } function noop() {} if (!window['console']) window['console']={'log':noop, 'error':noop}; var consoleNode, foreach = _.each, extend = _.extend, jQuery = window['jQuery'], msie = jQuery['browser']['msie'], angular = window['angular'] || (window['angular'] = {}), angularValidator = angular['validator'] || (angular['validator'] = {}), angularFilter = angular['filter'] || (angular['filter'] = {}), angularCallbacks = angular['callbacks'] || (angular['callbacks'] = {}), angularAlert = angular['alert'] || (angular['alert'] = function(){ log(arguments); window.alert.apply(window, arguments); }); function log(a, b, c){ var console = window['console']; switch(arguments.length) { case 1: console['log'](a); break; case 2: console['log'](a, b); break; default: console['log'](a, b, c); break; } } function error(a, b, c){ var console = window['console']; switch(arguments.length) { case 1: console['error'](a); break; case 2: console['error'](a, b); break; default: console['error'](a, b, c); break; } } function consoleLog(level, objs) { var log = document.createElement("div"); log.className = level; var msg = ""; var sep = ""; for ( var i = 0; i < objs.length; i++) { var obj = objs[i]; msg += sep + (typeof obj == 'string' ? obj : toJson(obj)); sep = " "; } log.appendChild(document.createTextNode(msg)); consoleNode.appendChild(log); } function isNode(inp) { return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute; } function isLeafNode (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; default: return false; } } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function escapeHtml(html) { if (!html || !html.replace) return html; return html. replace(/&/g, '&'). replace(//g, '>'); } function escapeAttr(html) { if (!html || !html.replace) return html; return html.replace(//g, '>').replace(/\"/g, '"'); } function bind(_this, _function) { if (!_this) throw "Missing this"; if (!_.isFunction(_function)) throw "Missing function"; return function() { return _function.apply(_this, arguments); }; } function shiftBind(_this, _function) { return function() { var args = [ this ]; for ( var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } return _function.apply(_this, args); }; } function outerHTML(node) { var temp = document.createElement('div'); temp.appendChild(node); var outerHTML = temp.innerHTML; temp.removeChild(node); return outerHTML; } function trim(str) { return str.replace(/^ */, '').replace(/ *$/, ''); } function toBoolean(value) { var v = ("" + value).toLowerCase(); if (v == 'f' || v == '0' || v == 'false' || v == 'no') value = false; return !!value; } function merge(src, dst) { for ( var key in src) { var value = dst[key]; var type = typeof value; if (type == 'undefined') { dst[key] = fromJson(toJson(src[key])); } else if (type == 'object' && value.constructor != array && key.substring(0, 1) != "$") { merge(src[key], value); } } } // //////////////////////////// // Loader // //////////////////////////// function Loader(document, head, config) { this.document = jQuery(document); this.head = jQuery(head); this.config = config; this.location = window.location; } Loader.prototype = { load: function() { this.configureLogging(); log("Server: " + this.config.server); this.configureJQueryPlugins(); this.computeConfiguration(); this.bindHtml(); }, configureJQueryPlugins: function() { log('Loader.configureJQueryPlugins()'); jQuery['fn']['scope'] = function() { var element = this; while (element && element.get(0)) { var scope = element.data("scope"); if (scope) return scope; element = element.parent(); } return null; }; jQuery['fn']['controller'] = function() { return this.data('controller') || NullController.instance; }; }, uid: function() { return "" + new Date().getTime(); }, computeConfiguration: function() { var config = this.config; if (!config.database) { var match = config.server.match(/https?:\/\/([\w]*)/); config.database = match ? match[1] : "$MEMORY"; } }, bindHtml: function() { log('Loader.bindHtml()'); var watcher = new UrlWatcher(this.location); var document = this.document; var widgetFactory = new WidgetFactory(this.config.server, this.config.database); var binder = new Binder(document[0], widgetFactory, watcher, this.config); widgetFactory.onChangeListener = shiftBind(binder, binder.updateModel); var controlBar = new ControlBar(document.find('body'), this.config.server); var onUpdate = function(){binder.updateView();}; var server = this.config.database=="$MEMORY" ? new FrameServer(this.window) : new Server(this.config.server, jQuery.getScript); server = new VisualServer(server, new Status(jQuery(document.body)), onUpdate); var users = new Users(server, controlBar); var databasePath = '/data/' + this.config.database; var post = function(request, callback){ server.request("POST", databasePath, request, callback); }; var datastore = new DataStore(post, users, binder.anchor); binder.updateListeners.push(function(){datastore.flush();}); var scope = new Scope( { '$anchor' : binder.anchor, '$binder' : binder, '$config' : this.config, '$console' : window.console, '$datastore' : datastore, '$save' : function(callback) { datastore.saveScope(scope.state, callback, binder.anchor); }, '$window' : window, '$uid' : this.uid, '$users' : users }, "ROOT"); document.data('scope', scope); log('$binder.entity()'); binder.entity(scope); log('$binder.compile()'); binder.compile(); log('ControlBar.bind()'); controlBar.bind(); log('$users.fetchCurrentUser()'); function fetchCurrentUser() { users.fetchCurrentUser(function(u) { if (!u && document.find("[ng-auth=eager]").length) { users.login(); } }); } fetchCurrentUser(); log('PopUp.bind()'); new PopUp(document).bind(); log('$binder.parseAnchor()'); binder.parseAnchor(); log('$binder.executeInit()'); binder.executeInit(); log('$binder.updateView()'); binder.updateView(); //watcher.listener = bind(binder, binder.onUrlChange, watcher); //watcher.onUpdate = function(){alert("update");}; //watcher.watch(); document.find("body").show(); log('ready()'); }, visualPost: function(delegate) { var status = new Status(jQuery(document.body)); return function(request, delegateCallback) { status.beginRequest(request); var callback = function() { status.endRequest(); try { delegateCallback.apply(this, arguments); } catch (e) { alert(toJson(e)); } }; delegate(request, callback); }; }, configureLogging: function() { var url = window.location.href + '#'; url = url.split('#')[1]; var config = { debug : null }; var configs = url.split('&'); for ( var i = 0; i < configs.length; i++) { var part = (configs[i] + '=').split('='); config[part[0]] = part[1]; } if (config.debug == 'console') { consoleNode = document.createElement("div"); consoleNode.id = 'ng-console'; document.getElementsByTagName('body')[0].appendChild(consoleNode); log = function() { consoleLog('ng-console-info', arguments); }; console.error = function() { consoleLog('ng-console-error', arguments); }; } }, loadCss: function(css) { var cssTag = document.createElement('link'); cssTag.rel = "stylesheet"; cssTag.type = "text/css"; if (!css.match(/^http:/)) css = this.config.server + css; cssTag.href = css; this.head[0].appendChild(cssTag); } }; function UrlWatcher(location) { this.location = location; this.delay = 25; this.setTimeout = function(fn, delay) { window.setTimeout(fn, delay); }; this.listener = function(url) { return url; }; this.expectedUrl = location.href; } UrlWatcher.prototype = { watch: function() { var self = this; var pull = function() { if (self.expectedUrl !== self.location.href) { var notify = self.location.hash.match(/^#\$iframe_notify=(.*)$/); if (notify) { if (!self.expectedUrl.match(/#/)) { self.expectedUrl += "#"; } self.location.href = self.expectedUrl; var id = '_iframe_notify_' + notify[1]; var notifyFn = angularCallbacks[id]; delete angularCallbacks[id]; try { (notifyFn||noop)(); } catch (e) { alert(e); } } else { self.listener(self.location.href); self.expectedUrl = self.location.href; } } self.setTimeout(pull, self.delay); }; pull(); }, setUrl: function(url) { // var existingURL = window.location.href; // if (!existingURL.match(/#/)) // existingURL += '#'; // if (existingURL != url) // window.location.href = url; // this.existingURL = url; }, getUrl: function() { return window.location.href; } }; angular['compile'] = function(root, config) { config = config || {}; var defaults = { 'server': "", 'addUrlChangeListener': noop }; //todo: don't start watcher var loader = new Loader(root, jQuery("head"), _(defaults).extend(config)); //todo: don't load stylesheet by default // loader.loadCss('/stylesheets/jquery-ui/smoothness/jquery-ui-1.7.1.css'); // loader.loadCss('/stylesheets/css'); loader.load(); var scope = jQuery(root).scope(); //TODO: cleanup return { 'updateView':function(){return scope.updateView.apply(scope, arguments);}, 'set':function(){return scope.set.apply(scope, arguments);}, 'get':function(){return scope.get.apply(scope, arguments);} }; };var angularGlobal = { 'typeOf':function(obj){ if (obj === null) return "null"; var type = typeof obj; if (type == "object") { if (obj instanceof Array) return "array"; if (obj instanceof Date) return "date"; if (obj.nodeType == 1) return "element"; } return type; } }; var angularCollection = {}; var angularObject = {}; var angularArray = { 'includeIf':function(array, value, condition) { var index = _.indexOf(array, value); if (condition) { if (index == -1) array.push(value); } else { array.splice(index, 1); } return array; }, 'sum':function(array, expression) { var fn = angular['Function']['compile'](expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, 'remove':function(array, value) { var index = _.indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, 'find':function(array, condition, defaultValue) { if (!condition) return undefined; var fn = angular['Function']['compile'](condition); _.detect(array, function($){ if (fn($)){ defaultValue = $; return true; } }); return defaultValue; }, 'findById':function(array, id) { return angular.Array.find(array, function($){return $.$id == id;}, null); }, 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var getter = Scope.getter; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function(){ var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function(){ var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case "function": predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, 'add':function(array, value) { array.push(_.isUndefined(value)? {} : value); return array; }, 'count':function(array, condition) { if (!condition) return array.length; var fn = angular['Function']['compile'](condition); return _.reduce(array, 0, function(count, $){return count + (fn($)?1:0);}); }, 'orderBy':function(array, expression, descend) { function reverse(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } expression = _.isArray(expression) ? expression: [expression]; expression = _.map(expression, function($){ var descending = false; if (typeof $ == "string" && ($.charAt(0) == '+' || $.charAt(0) == '-')) { descending = $.charAt(0) == '-'; $ = $.substring(1); } var get = $ ? angular['Function']['compile']($) : _.identity; return reverse(function(a,b){ return compare(get(a),get(b)); }, descending); }); var comparator = function(o1, o2){ for ( var i = 0; i < expression.length; i++) { var comp = expression[i](o1, o2); if (comp !== 0) return comp; } return 0; }; return _.clone(array).sort(reverse(comparator, descend)); }, 'orderByToggle':function(predicate, attribute) { var STRIP = /^([+|-])?(.*)/; var ascending = false; var index = -1; _.detect(predicate, function($, i){ if ($ == attribute) { ascending = true; index = i; return true; } if (($.charAt(0)=='+'||$.charAt(0)=='-') && $.substring(1) == attribute) { ascending = $.charAt(0) == '+'; index = i; return true; } }); if (index >= 0) { predicate.splice(index, 1); } predicate.unshift((ascending ? "-" : "+") + attribute); return predicate; }, 'orderByDirection':function(predicate, attribute, ascend, descend) { ascend = ascend || 'ng-ascend'; descend = descend || 'ng-descend'; var att = predicate[0] || ''; var direction = true; if (att.charAt(0) == '-') { att = att.substring(1); direction = false; } else if(att.charAt(0) == '+') { att = att.substring(1); } return att == attribute ? (direction ? ascend : descend) : ""; }, 'merge':function(array, index, mergeValue) { var value = array[index]; if (!value) { value = {}; array[index] = value; } merge(mergeValue, value); return array; } }; var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, 'toDate':function(string){ var match; if (typeof string == 'string' && (match = string.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4], match[5], match[6], 0); return date; } return string; } }; var angularDate = { 'toString':function(date){ function pad(n) { return n < 10 ? "0" + n : n; } return (date.getUTCFullYear()) + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + 'Z'; } }; var angularFunction = { 'compile':function(expression) { if (_.isFunction(expression)){ return expression; } else if (expression){ var scope = new Scope(); return function($) { scope.state = $; return scope.eval(expression); }; } else { return function($){return $;}; } } }; function defineApi(dst, chain, underscoreNames){ var lastChain = _.last(chain); foreach(underscoreNames, function(name){ lastChain[name] = _[name]; }); angular[dst] = angular[dst] || {}; foreach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal], ['extend', 'clone','isEqual', 'isElement', 'isArray', 'isFunction', 'isUndefined']); defineApi('Collection', [angularGlobal, angularCollection], ['each', 'map', 'reduce', 'reduceRight', 'detect', 'select', 'reject', 'all', 'any', 'include', 'invoke', 'pluck', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size']); defineApi('Array', [angularGlobal, angularCollection, angularArray], ['first', 'last', 'compact', 'flatten', 'without', 'uniq', 'intersect', 'zip', 'indexOf', 'lastIndexOf']); defineApi('Object', [angularGlobal, angularCollection, angularObject], ['keys', 'values']); defineApi('String', [angularGlobal, angularString], []); defineApi('Date', [angularGlobal, angularDate], []); defineApi('Function', [angularGlobal, angularCollection, angularFunction], ['bind', 'bindAll', 'delay', 'defer', 'wrap', 'compose']); function Binder(doc, widgetFactory, urlWatcher, config) { this.doc = doc; this.urlWatcher = urlWatcher; this.anchor = {}; this.widgetFactory = widgetFactory; this.config = config || {}; this.updateListeners = []; } Binder.parseBindings = function(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; }; Binder.hasBinding = function(string) { var bindings = Binder.parseBindings(string); return bindings.length > 1 || Binder.binding(bindings[0]) !== null; }; Binder.binding = function(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : null; }; Binder.prototype = { parseQueryString: function(query) { var params = {}; query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function (match, left, right) { if (left) params[decodeURIComponent(left)] = decodeURIComponent(right); }); return params; }, parseAnchor: function(url) { var self = this; url = url || this.urlWatcher.getUrl(); var anchorIndex = url.indexOf('#'); if (anchorIndex < 0) return; var anchor = url.substring(anchorIndex + 1); var anchorQuery = this.parseQueryString(anchor); foreach(self.anchor, function(newValue, key) { delete self.anchor[key]; }); foreach(anchorQuery, function(newValue, key) { self.anchor[key] = newValue; }); }, onUrlChange: function (url) { log("URL change detected", url); this.parseAnchor(url); this.updateView(); }, updateAnchor: function() { var url = this.urlWatcher.getUrl(); var anchorIndex = url.indexOf('#'); if (anchorIndex > -1) url = url.substring(0, anchorIndex); url += "#"; var sep = ''; for (var key in this.anchor) { var value = this.anchor[key]; if (typeof value === 'undefined' || value === null) { delete this.anchor[key]; } else { url += sep + encodeURIComponent(key); if (value !== true) url += "=" + encodeURIComponent(value); sep = '&'; } } this.urlWatcher.setUrl(url); return url; }, updateView: function() { var start = new Date().getTime(); var scope = jQuery(this.doc).scope(); scope.set("$invalidWidgets", []); scope.updateView(); var end = new Date().getTime(); this.updateAnchor(); _.each(this.updateListeners, function(fn) {fn();}); }, docFindWithSelf: function(exp){ var doc = jQuery(this.doc); var selection = doc.find(exp); if (doc.is(exp)){ selection = selection.andSelf(); } return selection; }, executeInit: function() { this.docFindWithSelf("[ng-init]").each(function() { var jThis = jQuery(this); var scope = jThis.scope(); try { scope.eval(jThis.attr('ng-init')); } catch (e) { alert("EVAL ERROR:\n" + jThis.attr('ng-init') + '\n' + toJson(e, true)); } }); }, entity: function (scope) { this.docFindWithSelf("[ng-entity]").attr("ng-watch", function() { try { var jNode = jQuery(this); var decl = scope.entity(jNode.attr("ng-entity")); return decl + (jNode.attr('ng-watch') || ""); } catch (e) { alert(e); } }); }, compile: function() { var jNode = jQuery(this.doc); var self = this; if (this.config.autoSubmit) { var submits = this.docFindWithSelf(":submit").not("[ng-action]"); submits.attr("ng-action", "$save()"); submits.not(":disabled").not("ng-bind-attr").attr("ng-bind-attr", '{disabled:"{{$invalidWidgets}}"}'); } this.precompile(this.doc)(this.doc, jNode.scope(), ""); this.docFindWithSelf("a[ng-action]").live('click', function (event) { var jNode = jQuery(this); try { jNode.scope().eval(jNode.attr('ng-action')); jNode.removeAttr('ng-error'); jNode.removeClass("ng-exception"); } catch (e) { jNode.addClass("ng-exception"); jNode.attr('ng-error', toJson(e, true)); } self.updateView(); return false; }); }, translateBinding: function(node, parentPath, factories) { var path = parentPath.concat(); var offset = path.pop(); var parts = Binder.parseBindings(node.nodeValue); if (parts.length > 1 || Binder.binding(parts[0])) { var parent = node.parentNode; if (isLeafNode(parent)) { parent.setAttribute('ng-bind-template', node.nodeValue); factories.push({path:path, fn:function(node, scope, prefix) { return new BindUpdater(node, node.getAttribute('ng-bind-template')); }}); } else { for (var i = 0; i < parts.length; i++) { var part = parts[i]; var binding = Binder.binding(part); var newNode; if (binding) { newNode = document.createElement("span"); var jNewNode = jQuery(newNode); jNewNode.attr("ng-bind", binding); if (i === 0) { factories.push({path:path.concat(offset + i), fn:this.ng_bind}); } } else if (msie && part.charAt(0) == ' ') { newNode = document.createElement("span"); newNode.innerHTML = ' ' + part.substring(1); } else { newNode = document.createTextNode(part); } parent.insertBefore(newNode, node); } } parent.removeChild(node); } }, precompile: function(root) { var factories = []; this.precompileNode(root, [], factories); return function (template, scope, prefix) { var len = factories.length; for (var i = 0; i < len; i++) { var factory = factories[i]; var node = template; var path = factory.path; for (var j = 0; j < path.length; j++) { node = node.childNodes[path[j]]; } try { scope.addWidget(factory.fn(node, scope, prefix)); } catch (e) { alert(e); } } }; }, precompileNode: function(node, path, factories) { var nodeType = node.nodeType; if (nodeType == Node.TEXT_NODE) { this.translateBinding(node, path, factories); return; } else if (nodeType != Node.ELEMENT_NODE && nodeType != Node.DOCUMENT_NODE) { return; } if (!node.getAttribute) return; var nonBindable = node.getAttribute('ng-non-bindable'); if (nonBindable || nonBindable === "") return; var attributes = node.attributes; if (attributes) { var bindings = node.getAttribute('ng-bind-attr'); node.removeAttribute('ng-bind-attr'); bindings = bindings ? fromJson(bindings) : {}; var attrLen = attributes.length; for (var i = 0; i < attrLen; i++) { var attr = attributes[i]; var attrName = attr.name; // http://www.glennjones.net/Post/809/getAttributehrefbug.htm var attrValue = msie && attrName == 'href' ? decodeURI(node.getAttribute(attrName, 2)) : attr.value; if (Binder.hasBinding(attrValue)) { bindings[attrName] = attrValue; } } var json = toJson(bindings); if (json.length > 2) { node.setAttribute("ng-bind-attr", json); } } if (!node.getAttribute) log(node); var repeaterExpression = node.getAttribute('ng-repeat'); if (repeaterExpression) { node.removeAttribute('ng-repeat'); var precompiled = this.precompile(node); var view = document.createComment("ng-repeat: " + repeaterExpression); var parentNode = node.parentNode; parentNode.insertBefore(view, node); parentNode.removeChild(node); function template(childScope, prefix, i) { var clone = jQuery(node).clone(); clone.css('display', ''); clone.attr('ng-repeat-index', "" + i); clone.data('scope', childScope); precompiled(clone[0], childScope, prefix + i + ":"); return clone; } factories.push({path:path, fn:function(node, scope, prefix) { return new RepeaterUpdater(jQuery(node), repeaterExpression, template, prefix); }}); return; } if (node.getAttribute('ng-eval')) factories.push({path:path, fn:this.ng_eval}); if (node.getAttribute('ng-bind')) factories.push({path:path, fn:this.ng_bind}); if (node.getAttribute('ng-bind-attr')) factories.push({path:path, fn:this.ng_bind_attr}); if (node.getAttribute('ng-hide')) factories.push({path:path, fn:this.ng_hide}); if (node.getAttribute('ng-show')) factories.push({path:path, fn:this.ng_show}); if (node.getAttribute('ng-class')) factories.push({path:path, fn:this.ng_class}); if (node.getAttribute('ng-class-odd')) factories.push({path:path, fn:this.ng_class_odd}); if (node.getAttribute('ng-class-even')) factories.push({path:path, fn:this.ng_class_even}); if (node.getAttribute('ng-style')) factories.push({path:path, fn:this.ng_style}); if (node.getAttribute('ng-watch')) factories.push({path:path, fn:this.ng_watch}); var nodeName = node.nodeName; if ((nodeName == 'INPUT' ) || nodeName == 'TEXTAREA' || nodeName == 'SELECT' || nodeName == 'BUTTON') { var self = this; factories.push({path:path, fn:function(node, scope, prefix) { node.name = prefix + node.name.split(":").pop(); return self.widgetFactory.createController(jQuery(node), scope); }}); } if (nodeName == 'OPTION') { var html = jQuery('' + '' + '' + '' + ''); }; FileController.prototype = { '_on_cancel': noop, '_on_complete': noop, '_on_httpStatus': function(status) { alert("httpStatus:" + this.scopeName + " status:" + status); }, '_on_ioError': function() { alert("ioError:" + this.scopeName); }, '_on_open': function() { alert("open:" + this.scopeName); }, '_on_progress':noop, '_on_securityError': function() { alert("securityError:" + this.scopeName); }, '_on_uploadCompleteData': function(data) { var value = fromJson(data); value.url = this.attachmentsPath + '/' + value.id + '/' + value.text; this.view.find("input").attr('checked', true); var scope = this.view.scope(); this.value = value; this.updateModel(scope); this.value = null; scope.get('$binder').updateView(); }, '_on_select': function(name, size, type) { this.name = name; this.view.find("a").text(name).attr('href', name); this.view.find("span").text(angular['filter']['bytes'](size)); this.upload(); }, updateModel: function(scope) { var isChecked = this.view.find("input").attr('checked'); var value = isChecked ? this.value : null; if (this.lastValue === value) { return false; } else { scope.set(this.scopeName, value); return true; } }, updateView: function(scope) { var modelValue = scope.get(this.scopeName); if (modelValue && this.value !== modelValue) { this.value = modelValue; this.view.find("a"). attr("href", this.value.url). text(this.value.text); this.view.find("span").text(angular['filter']['bytes'](this.value.size)); } this.view.find("input").attr('checked', !!modelValue); }, upload: function() { if (this.name) { this.uploader.uploadFile(this.attachmentsPath); } } }; /////////////////////// // NullController /////////////////////// function NullController(view) {this.view = view;}; NullController.prototype = { updateModel: function() { return true; }, updateView: noop }; NullController.instance = new NullController(); /////////////////////// // ButtonController /////////////////////// var ButtonController = NullController; /////////////////////// // TextController /////////////////////// function TextController(view, exp) { this.view = view; this.exp = exp; this.validator = view.getAttribute('ng-validate'); this.required = typeof view.attributes['ng-required'] != "undefined"; this.lastErrorText = null; this.lastValue = undefined; this.initialValue = view.value; var widget = view.getAttribute('ng-widget'); if (widget === 'datepicker') { jQuery(view).datepicker(); } }; TextController.prototype = { updateModel: function(scope) { var value = this.view.value; if (this.lastValue === value) { return false; } else { scope.setEval(this.exp, value); this.lastValue = value; return true; } }, updateView: function(scope) { var view = this.view; var value = scope.get(this.exp); if (typeof value === "undefined") { value = this.initialValue; scope.setEval(this.exp, value); } value = value ? value : ''; if (this.lastValue != value) { view.value = value; this.lastValue = value; } var isValidationError = false; view.removeAttribute('ng-error'); if (this.required) { isValidationError = !(value && value.length > 0); } var errorText = isValidationError ? "Required Value" : null; if (!isValidationError && this.validator && value) { errorText = scope.validate(this.validator, value); isValidationError = !!errorText; } if (this.lastErrorText !== errorText) { this.lastErrorText = isValidationError; if (errorText !== null) { view.setAttribute('ng-error', errorText); scope.markInvalid(this); } jQuery(view).toggleClass('ng-validation-error', isValidationError); } } }; /////////////////////// // CheckboxController /////////////////////// function CheckboxController(view, exp) { this.view = view; this.exp = exp; this.lastValue = undefined; this.initialValue = view.checked ? view.value : ""; }; CheckboxController.prototype = { updateModel: function(scope) { var input = this.view; var value = input.checked ? input.value : ''; if (this.lastValue === value) { return false; } else { scope.setEval(this.exp, value); this.lastValue = value; return true; } }, updateView: function(scope) { var input = this.view; var value = scope.eval(this.exp); if (typeof value === "undefined") { value = this.initialValue; scope.setEval(this.exp, value); } input.checked = input.value == (''+value); } }; /////////////////////// // SelectController /////////////////////// function SelectController(view, exp) { this.view = view; this.exp = exp; this.lastValue = undefined; this.initialValue = view.value; }; SelectController.prototype = { updateModel: function(scope) { var input = this.view; if (input.selectedIndex < 0) { scope.setEval(this.exp, null); } else { var value = this.view.value; if (this.lastValue === value) { return false; } else { scope.setEval(this.exp, value); this.lastValue = value; return true; } } }, updateView: function(scope) { var input = this.view; var value = scope.get(this.exp); if (typeof value === 'undefined') { value = this.initialValue; scope.setEval(this.exp, value); } if (value !== this.lastValue) { input.value = value ? value : ""; this.lastValue = value; } } }; /////////////////////// // MultiSelectController /////////////////////// function MultiSelectController(view, exp) { this.view = view; this.exp = exp; this.lastValue = undefined; this.initialValue = this.selected(); }; MultiSelectController.prototype = { selected: function () { var value = []; var options = this.view.options; for ( var i = 0; i < options.length; i++) { var option = options[i]; if (option.selected) { value.push(option.value); } } return value; }, updateModel: function(scope) { var value = this.selected(); // TODO: This is wrong! no caching going on here as we are always comparing arrays if (this.lastValue === value) { return false; } else { scope.setEval(this.exp, value); this.lastValue = value; return true; } }, updateView: function(scope) { var input = this.view; var selected = scope.get(this.exp); if (typeof selected === "undefined") { selected = this.initialValue; scope.setEval(this.exp, selected); } if (selected !== this.lastValue) { var options = input.options; for ( var i = 0; i < options.length; i++) { var option = options[i]; option.selected = _.include(selected, option.value); } this.lastValue = selected; } } }; /////////////////////// // RadioController /////////////////////// function RadioController(view, exp) { this.view = view; this.exp = exp; this.lastChecked = undefined; this.lastValue = undefined; this.inputValue = view.value; this.initialValue = view.checked ? view.value : null; }; RadioController.prototype = { updateModel: function(scope) { var input = this.view; if (this.lastChecked) { return false; } else { input.checked = true; this.lastValue = scope.setEval(this.exp, this.inputValue); this.lastChecked = true; return true; } }, updateView: function(scope) { var input = this.view; var value = scope.get(this.exp); if (this.initialValue && typeof value === "undefined") { value = this.initialValue; scope.setEval(this.exp, value); } if (this.lastValue != value) { this.lastChecked = input.checked = this.inputValue == (''+value); this.lastValue = value; } } }; /////////////////////// //ElementController /////////////////////// function BindUpdater(view, exp) { this.view = view; this.exp = Binder.parseBindings(exp); this.hasError = false; this.scopeSelf = {element:view}; }; BindUpdater.toText = function(obj) { var e = escapeHtml; switch(typeof obj) { case "string": case "boolean": case "number": return e(obj); case "function": return BindUpdater.toText(obj()); case "object": if (isNode(obj)) { return outerHTML(obj); } else if (obj instanceof angular.filter.Meta) { switch(typeof obj.html) { case "string": case "number": return obj.html; case "function": return obj.html(); case "object": if (isNode(obj.html)) return outerHTML(obj.html); default: break; } switch(typeof obj.text) { case "string": case "number": return e(obj.text); case "function": return e(obj.text()); default: break; } } if (obj === null) return ""; return e(toJson(obj, true)); default: return ""; } }; BindUpdater.prototype = { updateModel: noop, updateView: function(scope) { var html = []; var parts = this.exp; var length = parts.length; for(var i=0; i iteratorLength; --r) { var unneeded = this.children.pop().element[0]; unneeded.parentNode.removeChild(unneeded); } // Special case for option in select if (child && child.element[0].nodeName === "OPTION") { var select = jQuery(child.element[0].parentNode); var cntl = select.data('controller'); if (cntl) { cntl.lastValue = undefined; cntl.updateView(scope); } } }); } }; ////////////////////////////////// // PopUp ////////////////////////////////// function PopUp(doc) { this.doc = doc; }; PopUp.OUT_EVENT = "mouseleave mouseout click dblclick keypress keyup"; PopUp.onOver = function(e) { PopUp.onOut(); var jNode = jQuery(this); jNode.bind(PopUp.OUT_EVENT, PopUp.onOut); var position = jNode.position(); var de = document.documentElement; var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var hasArea = w - position.left; var width = 300; var title = jNode.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."; var msg = jNode.attr("ng-error"); var x; var arrowPos = hasArea>(width+75) ? "left" : "right"; var tip = jQuery( "
" + "
" + "
"+title+"
" + "
"+msg+"
" + "
"); jQuery("body").append(tip); if(arrowPos === 'left'){ x = position.left + this.offsetWidth + 11; }else{ x = position.left - (width + 15); tip.find('.ng-arrow-right').css({left:width+1}); } tip.css({left: x+"px", top: (position.top - 3)+"px"}); return true; }; PopUp.onOut = function() { jQuery('#ng-callout'). unbind(PopUp.OUT_EVENT, PopUp.onOut). remove(); return true; }; PopUp.prototype = { bind: function () { var self = this; this.doc.find('.ng-validation-error,.ng-exception'). live("mouseover", PopUp.onOver); } }; ////////////////////////////////// // Status ////////////////////////////////// function Status(body) { this.loader = body.append(Status.DOM).find("#ng-loading"); this.requestCount = 0; }; Status.DOM ='
loading....
'; Status.prototype = { beginRequest: function () { if (this.requestCount === 0) { this.loader.show(); } this.requestCount++; }, endRequest: function () { this.requestCount--; if (this.requestCount === 0) { this.loader.hide("fold"); } } }; })(window, document);