<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Szymon Kosno on Medium]]></title>
        <description><![CDATA[Stories by Szymon Kosno on Medium]]></description>
        <link>https://medium.com/@skosno?source=rss-b283b097ae18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dpN9dOZITlG2E0h8zCQyHA.jpeg</url>
            <title>Stories by Szymon Kosno on Medium</title>
            <link>https://medium.com/@skosno?source=rss-b283b097ae18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:25:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skosno/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AngularJS: Did you know…? From 1.3 to 1.4, with some extra]]></title>
            <link>https://medium.com/@skosno/angularjs-did-you-know-from-1-3-to-1-4-with-some-extra-51c3aa759494?source=rss-b283b097ae18------2</link>
            <guid isPermaLink="false">https://medium.com/p/51c3aa759494</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Szymon Kosno]]></dc:creator>
            <pubDate>Tue, 24 Nov 2015 17:32:47 GMT</pubDate>
            <atom:updated>2015-11-25T11:06:31.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*vNhaw1SCSu_DuKwSHZSQnQ.png" /></figure><p>This is a continuation of “<a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-1-171fd93b9d4b">AngularJS: Did you know…? From 1.0 to 1.3, part 1</a> and <a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-2-3a40b8c7270e">part 2</a>” focusing on functionalities made available around version 1.3–1.4.</p><p>For those who did not see previous posts — this is a list of functionalities made available in AngularJS that you might have missed or were not announced in a clear way.</p><p>DISCLAIMER! This is not a change log or tutorial — it is just a list of features that might have been overlooked when working with Angular.</p><h3>What features were introduced?</h3><ol><li><strong>You can now force usage of jqLite or specific version of jQuery in your application with ng-jq introduced</strong></li></ol><pre><em>//force usage of jqLite<br></em>&lt;html ng-app <strong>ng-jq</strong>&gt;</pre><pre><em>//force usage of specific jQueryLin variable in window<br></em>&lt;html ng-app <strong>ng-jq=”jQueryLib”</strong>&gt;</pre><p><a href="https://code.angularjs.org/1.4.8/docs/api/ng/directive/ngJq">See more in documentation.</a></p><p>I really RECOMMEND that you stop using automatic jQuery wrapping. Mainly because it is really confusing to use jQuery API by assuming element will expose it — in my opinion it is so much better to explicitly say in your component that jQuery will be used (if you need it). <a href="http://blog.mikie.iki.fi/2014/04/why-is-angularjs-slower-with-jquery.html">Additionally you will get performance benefit.</a></p><p><strong>WARNING!</strong> This functionality is a bit confusing — it does not matter if “ng-jq” is defined on element next to ng-app. In fact it is not connected to bootstrapping at all! Angular will try to find ng-jq (and variants) using “document.querySelector” when loading angular.js, not when you bootstrap your application… So if you have your scripts in &lt;head&gt; for some reason, you need to define “ng-jq” on &lt;html&gt; tag because &lt;body&gt; and other elements will not be there yet…</p><p><strong>2. Number filter now renders “\u221e” (∞) if value is infinity</strong></p><p><strong>3. “limitTo” will ignore limit if invalid value (return unchanged value)</strong></p><p><strong>4. Date filter and ngModelOptions now accepts timezones other than UTC (and GTM for ngModel); specify it as offset ‘+0500’</strong></p><p><strong>5. You can now bind scope to controller instance using a bit cleaner approach (old way still works though)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54763f08b3b5c1b754ed9419e171f69b/href">https://medium.com/media/54763f08b3b5c1b754ed9419e171f69b/href</a></iframe><p><strong>6. $cookies is now standard getter/setter = there is no “magic” happening behind stage to synchronise values and expose them directly on $cookies (and that is good)</strong></p><pre>The new API on $cookies is as follows:<br>• get<br>• put<br>• getObject<br>• putObject<br>• getAll<br>• remove</pre><p><strong>CAUTION!</strong> You might be using <a href="https://github.com/gsklee/ngStorage">ngStorage</a> module for local/session storage that aimed to provide similar functionality as initial version of ngCookies. As such it has similar issues — what it does is a deep comparison of stored data (using angular.equals) on pretty much <em>every digest cycle. </em>If you store something big in storage… it will cost you a lot. In such case go for getter/setter approach (like <a href="https://github.com/grevory/angular-local-storage">angular-local-storage</a> or <a href="https://github.com/search?utf8=%E2%9C%93&amp;q=angular+local+storage">many others</a>).</p><p><strong>7. $cookieStore is now DEPRECATED, so stop using or write your own if needed</strong></p><p><strong>8. You can now use angular.merge — It does a deep copy of all properties from source to destination preserving properties in child objects</strong></p><p><strong>9. You can now write your own custom params serializers for $http methods</strong><br>So now you can decide how params object will be represented in URL — you can do it by extending “config” of any $http method that accepts it, with “paramSerializer” key :</p><pre><strong>paramSerializer</strong> — {string|function(Object&lt;string,string&gt;):string} — A function used to prepare the string representation of request parameters (specified as an object). If specified as string, it is interpreted as function registered with the <a href="https://code.angularjs.org/1.4.8/docs/api/auto/service/$injector">$injector</a>, which means you can create your own serializer by registering it as a <a href="https://code.angularjs.org/1.4.8/docs/api/auto/service/$provide#service">service</a>. The default serializer is the <a href="https://code.angularjs.org/1.4.8/docs/api/ng/service/$httpParamSerializer">$httpParamSerializer</a>; alternatively, you can use the <a href="https://code.angularjs.org/1.4.8/docs/api/ng/service/$httpParamSerializerJQLike">$httpParamSerializerJQLike</a></pre><p>Or it can be done in config phase with defaults in $httpProvider:</p><pre>module.config([&#39;$httpProvider&#39;, function($httpProvider) {<br>    $httpProvider.<strong>defaults.paramSerializer</strong> = &#39;$httpParamSerializerJQLike&#39;;<br>}]);</pre><p><strong>10. ngOptions now stores value type inside generated option</strong></p><pre><em>//before<br></em>&lt;option <strong>value=&quot;1&quot;</strong>&gt;a&lt;/option&gt;</pre><pre><em>//now<br></em>&lt;option <strong>value=&quot;string:a&quot;</strong>&gt;a&lt;/option&gt;</pre><p><strong>11. ngOptions when iterating Objects no longer iterates them alphabetically but with order of Object.keys(obj) (so basically same as in for..in = order is not guaranteed across browsers)</strong></p><p><strong>12. ngRepeat now iterates objects in order of „for key in obj” (again order is not guaranteed across browsers)</strong></p><p><a href="https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/">Exploring JavaScript for-in loops</a></p><p><strong>13. Directive “select” will now use strict comparison of the ngModel scope value against option values to determine which option is selected (so numbers are not compared to strings etc.)</strong></p><p><strong>14. You can now filter array like objects using filter called “filter”</strong></p><pre>function getArguments() {<br>  return arguments;<br>}<br>var <strong>argsObj</strong> = getArguments({name: ‘Misko’}, {name: ‘Igor’}, {name: ‘Brad’});</pre><pre>var <strong>nodeList</strong> = jqLite(“&lt;p&gt;&lt;span&gt;Misko&lt;/span&gt;&lt;span&gt;Igor&lt;/span&gt;&lt;span&gt;Brad&lt;/span&gt;&lt;/p&gt;”)[0].childNodes;</pre><pre>function nodeFilterPredicate(node) {<br>  return node.innerHTML.indexOf(“I”) !== -1;<br>}</pre><pre>//arguments are not really not an array, just array like<br>expect(filter(argsObj, ‘i’).length).toBe(2);</pre><pre>//string is array like<br>expect(filter(‘abc’,’b’).length).toBe(1); </pre><pre>//DOM nodes list is array like<br>expect(filter(nodeList, nodeFilterPredicate).length).toBe(1);</pre><p><strong>15. You can use .decorator helper in angular.module to register service decorators</strong></p><pre>angular.module(‘myApp’)<strong>.decorator</strong>(‘myService’, function($delegate) {<br>  $delegate.test = ‘bye’;<br>  return $delegate;<br>});</pre><p><strong>16. You can use $anchorScroll to scroll to specified element</strong></p><pre>$anchorScroll(hash);</pre><p><strong>17. When using controller in directive and not specifying “require”, post link will by default get current directive controller in ctrl parameter</strong></p><pre>{<br>  //require: &#39;myDirective&#39; //as you can see it is commented out<br>  <strong>link</strong>: function(scope, element, attrs, <strong>ctrl</strong>){} //yes we have controller here!<br>  controller: function(){}<br>}</pre><p><strong>18. $timeout and $interval allow passing additional parameters that will be passed to callbackFunction</strong></p><pre>var task1 = jasmine.createSpy(‘task1’);<br><strong>$interval</strong>(task1, 1000, 2, true, <strong>‘Task1’, ‘Task2’</strong>);<br>$window.flush(1000);<br>expect(task1).toHaveBeenCalledWith(‘Task1’, ‘Task2’);</pre><pre>var task2 = jasmine.createSpy(‘task2’);<br><strong>$timeout</strong>(task2, 1000, true, <strong>‘Task1’, ‘Task2’</strong>);<br>$window.flush(1000);<br>expect(task2).toHaveBeenCalledWith(‘Task1’, ‘Task2’);</pre><p><strong>19. ngClass allows both strings and objects in array (so that you can specify conditional classes when using array)</strong></p><pre>&lt;div ng-class=” [classVar, {‘is-active’: activeVar }] “&gt;</pre><p><strong>20. ngMessage directive now supports a new attribute called ng-message-exp which will evaluate an expression and will keep track of that expression as it changes in order to re-evaluate the listed messages</strong></p><pre><em>&lt;!-- </em>using attribute directives --&gt;<em><br></em>&lt;ANY ng-messages=”expression”&gt;<br>  &lt;ANY <strong>ng-message-exp</strong>=”expressionValue”&gt;…&lt;/ANY&gt;<br>&lt;/ANY&gt;</pre><pre><em>&lt;!-- </em>or by using element directives --&gt;<em><br></em>&lt;ng-messages for=”expression”&gt;<br>  &lt;ng-message <strong>when-exp</strong>=”expressionValue”&gt;…&lt;/ng-message&gt;<br>&lt;/ng-messages&gt;</pre><p>With this you can loop ng-messages in ng-repeat!</p><p><strong>21. ngMessagesInclude attribute has now been removed. Instead, ngMessagesInclude is to be used on its own element inline with other inline messages situated as children within the ngMessages container directive</strong></p><pre><em>&lt;!-- </em>AngularJS 1.3.x --&gt;<em><br>  </em>&lt;div ng-messages=”model.$error” <strong>ng-messages-include=”remote.html”</strong>&gt;<br>  &lt;div ng-message=”required”&gt;Your message is required&lt;/div&gt;<br>&lt;/div&gt;</pre><pre><em>&lt;!-- </em>AngularJS 1.4.x --&gt;<em><br></em>&lt;div ng-messages=”model.$error”&gt;<br>  &lt;div ng-message=”required”&gt;Your message is required&lt;/div&gt;<br>  <strong>&lt;div ng-messages-include=”remote.html”&gt;&lt;/div&gt;</strong><br>&lt;/div&gt;</pre><p><a href="http://blog.thoughtram.io/2015/06/06/ng-messages-revisited.html">ngMessages revisited</a></p><p><strong>22. The legacy methods &#39;success&#39; and &#39;error&#39; on promises returned by $http are now DEPRECATED.</strong></p><p>They are still in use and controlled by “useLegacyPromiseExtensions” that defaults to “true”, but will be set to “false” soon and then removed entirely.</p><p><strong>23. In inputs with ngModel, ngPattern and pattern directives will validate the regex against the viewValue of ngModel, i.e. the value of the model before the $parsers are applied.</strong></p><p>Previously, the modelValue (the result of the $parsers) was validated and that is not really something user is inputting…</p><p>IMPORTANT! If you rely on the pattern being validated against the modelValue, you must create your own validator directive that overwrites the built-in pattern validator. <a href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes-6">See example in changelog.</a></p><p><strong>24. You can now create custom xhr objects using $http by $xhrFactory</strong></p><pre>//Replace or decorate this service to create your own custom //XMLHttpRequest objects.</pre><pre>angular.module(‘myApp’, [])<br>  .factory(‘$xhrFactory’, function() {<br>    return function createXhr(method, url) {<br>      return new window.XMLHttpRequest({mozSystem: true});<br>    };<br>  });</pre><p><strong>25. Animations changed — Too much to write about, more information from author</strong></p><ul><li><a href="https://plus.google.com/+MatiasNiemel%C3%A4/posts/3wMhXTnim2s">Alright. Today&#39;s the big day. The release candidate for AngularJS 1.4 is out...</a></li><li><a href="http://slides.yearofmoo.com/ng-conf-2015/index.html#/0/0/">What&#39;s new in ngAnimate</a></li></ul><h3>EXTRA — transclusion magic with $compile and parentBoundTranscludeFn</h3><p><a href="https://github.com/angular/angular.js/issues/9413">When you are manually compiling HTML in a directive with transcluded content, it will use wrong scope unless you use something called “parentBoundTranscludeFn”.</a></p><p>The story is that we have directive that uses transclusion but it also chooses what template to use based on some conditions. Because we are requesting/choosing directive template in postLink, we also use $compile to compile results.</p><p>Normally you would do something like this:</p><pre>$compile(element.contents())(scope);</pre><p>But this will fail because there is a transcluded content in element. To make it work we use “well documented” feature:</p><pre>$compile(element.contents())(scope, undefined, {<strong>parentBoundTranscludeFn</strong>: transclude});</pre><p>In fact third paramter here is “options” object — An optional object hash with linking options. If options is provided, then the following keys may be used to control linking behavior:</p><ul><li>parentBoundTranscludeFn — the transclude function made available to directives; if given, it will be passed through to the link functions of directives found in element during compilation.</li><li>transcludeControllers — an object hash with keys that map controller names to controller instances; if given, it will make the controllers available to directives.</li><li>futureParentElement — defines the parent to which the cloneAttachFn will add the cloned elements; only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements). See also the directive.controller property.</li></ul><p><a href="https://code.angularjs.org/1.4.8/docs/api/ng/service/$compile">More on $compile can be found in official documentation.</a></p><p><a href="https://code.angularjs.org/1.4.8/docs/api/ng/service/$compile">AngularJS</a></p><h3>See you next time</h3><p>That’s all for today. Again I hope you have found something interesting in this list. As always I urge you to read full AngularJS change log to always be up-to-date:</p><p><a href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md">angular/angular.js</a></p><p>If you have not seen it I also recommend reviewing “<a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-1-171fd93b9d4b">AngularJS: Did you know…? From 1.0 to 1.3, part 1</a> and <a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-2-3a40b8c7270e">part 2</a>”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51c3aa759494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AngularJS: Did you know…? From 1.0 to 1.3, part 2]]></title>
            <link>https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-2-3a40b8c7270e?source=rss-b283b097ae18------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a40b8c7270e</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Szymon Kosno]]></dc:creator>
            <pubDate>Tue, 03 Nov 2015 17:53:25 GMT</pubDate>
            <atom:updated>2015-11-03T17:53:25.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*vNhaw1SCSu_DuKwSHZSQnQ.png" /></figure><p>This is a continuation of “<a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-1-171fd93b9d4b">AngularJS: Did you know…? From 1.0 to 1.3, part 1</a>” focusing on functionalities made available around version 1.0–1.3. I will follow up in another post focusing on changes introduced somewhere between 1.3–1.4.</p><p>DISCLAIMER! This is not a change log or tutorial — it is just a list of features that might have been overlooked when working with Angular.</p><h3>What features were introduced?</h3><p><strong>26. ngModel now has $validators pipeline (instead of using $formatters and $parsers pipelines to run validation code..)</strong></p><pre>require: ‘ngModel’,<br>link: function(scope, elm, attrs, ctrl) {<br>  if (ctrl &amp;&amp; ctrl.$validators.email) { <br>    <em>// this will overwrite the default Angular email validator<br>    </em>ctrl.<strong>$validators.email</strong> = function(modelValue, viewValue) {<br>      return ctrl.$isEmpty(modelValue) || <br>           EMAIL_REGEXP.test(modelValue);<br>    };<br>  }<br>}</pre><p><strong>27. ngModel now has $asyncValidators processed after sync validators</strong></p><pre>require: ‘ngModel’,<br>link: function(scope, elm, attrs, ctrl) {<br>  var usernames = [‘Jim’, ‘John’, ‘Jill’, ‘Jackie’];<br>  ctrl.<strong>$asyncValidators.username</strong> = function(modelValue, viewValue) {<br>    …<br>    return promise;<br>  };<br>}</pre><p><strong>28. When using $scope.$new you can now pass second parameter that will become the new scope’s parent</strong></p><pre>var isolated = $scope.$new(true);<br>var other = $scope.$new(false, isolated);</pre><p><strong>29. $anchorScroll supports a configurable vertical scroll offset</strong></p><pre>.run([‘$anchorScroll’, function($anchorScroll) {<br>  $anchorScroll.yOffset = 50; <em>// always scroll by 50 extra pixels<br></em>}])</pre><p><strong>30. You can use “*” in scope binding to force $watchCollection instead of $watch (directives)</strong></p><pre>scope: { prop: &#39;=*&#39; }</pre><p><strong>31. ngMaxlength (and maxlength) can be set to “-1” effectively disabling this check</strong></p><p><strong>32. Currency filter has fractionSize as optional parameter</strong></p><p><strong>33. ngModelController now exposes $setDirty function</strong></p><p><strong>34. Json filter accepts custom indentation by passing number of spaces</strong></p><p><strong>35. You can use camel cased attributes with ng-attr using snake case like “ng-attr-view_box” will become attribute “viewBox”</strong></p><p><strong>36. You can now pass context to $evalAsync execution</strong></p><pre>$rootScope.log = ‘’;<br>$rootScope.$evalAsync(‘log = log + a’, {a: 1});<br>$rootScope.$digest();<br>expect($rootScope.log).toBe(‘1’);</pre><p><strong>37. Falsy vales changed in expressions</strong></p><ul><li>values ‘f’, ‘0’, ‘false’, ‘no’, ’n’, ‘[]’ are no longer treated as falsy</li><li>only JavaScript falsy values are now treated as falsy by the expression parser; there are six of them: false, null, undefined, NaN, 0 and “”</li></ul><p><strong>38. $controller no longer looks for controllers on “window” object = global functions no longer are detected as controllers</strong></p><p><strong>39. You can NO LONGER use .bind, .call or .apply in expressions</strong></p><pre>scope.$eval(‘$eval.bind()’)</pre><p><strong>40. Angular.copy applies the prototype of the original object to the copied object instead of just copying everything from prototype to instance</strong></p><p><strong>41. You can NO LONGER access the isolated scope from attributes on the element where the isolated directive is defined!</strong></p><pre>&lt;isolated-directive some-attribute=”variableFromDirectiveScope”&gt;&lt;/isolated-directive&gt;</pre><p><strong>42. ng-pattern now accepts proper regular expressions — if string is given it will be matched literally</strong></p><pre><em>//before you could pass and ‘/i’ would be used as flag<br></em>this.exp = ‘/abc/i’;</pre><pre><em>//now please use proper regular expression<br></em>this.exp = /abc/i;</pre><p><strong>43. $cancelUpdate is now called $rollbackViewValue() and used to Cancel an update and reset the input element’s value to prevent an update to the $modelValue</strong></p><p><strong>44. Do not use directive “replace” as it is DEPRECATED</strong></p><p><strong>45. Additional watch — $watchGroup() that takes array of expressions to watch</strong></p><p><strong>46. Major update: ONE-TIME bindings — you can use them in any expression by using “::” in front of variable that you bind</strong></p><pre><em>&lt;! — </em>Markup: expression will not change once set <em>→<br></em>&lt;h1&gt;{{<strong>::title</strong> | uppercase}}&lt;h1&gt;<br>&lt;h1&gt;{{<strong>::getTitle()</strong>}}&lt;/h1&gt;<br>&lt;div style=”color: {{<strong>::color</strong>}}”&gt;{{<strong>::content</strong>}}&lt;/div&gt;</pre><pre><em>&lt;! — </em>within a directive <em>→<br></em>&lt;qrcode code=”<strong>::code</strong>”&gt;&lt;/qrcode&gt;<br>&lt;ul&gt;<br>  &lt;li ng-repeat=”item in <strong>::items</strong>”&gt;{{item.name}}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p><strong>47. Filters NO LONGER run if input did not change! So any injected data change will not re-render filter binding, unless you do</strong></p><pre>filter.$stateful = true</pre><p><strong>48. ngAria introduced — accessibility helper for angular directive</strong></p><p><a href="http://angularjs.blogspot.co.uk/2014/11/using-ngaria.html">AngularJS: Using ngAria</a></p><p><strong>49. ngMessages introduced — for easier reuse of error messages in forms (more modifications in 1.4)</strong></p><p><a href="http://www.yearofmoo.com/2014/05/how-to-use-ngmessages-in-angularjs.html">How to use ngMessages in AngularJS - yearofmoo.com</a></p><p><strong>50. ngHint introduced — to give you useful hints about Angular coding practices</strong></p><p><a href="http://blog.thoughtram.io/angularjs/2014/11/06/exploring-angular-1.3-angular-hint.html">Exploring Angular 1.3: Angular-hint</a></p><h3>See you next time — end of part 2</h3><p>This post concludes list of “did you know” for versions 1.0–1.3. As always I urge you to read full AngularJS change log to always be up-to-date:</p><p><a href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md">https://github.com/angular/angular.js/blob/master/CHANGELOG.md</a></p><p>If you have not seen it I also recommend reviewing part 1 of this post:</p><p><a href="https://medium.com/p/171fd93b9d4b"></a></p><p>I will update this post with link to next one focused on changes done somewhere between 1.3 and 1.4.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a40b8c7270e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AngularJS: Did you know…? From 1.0 to 1.3, part 1]]></title>
            <link>https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-1-171fd93b9d4b?source=rss-b283b097ae18------2</link>
            <guid isPermaLink="false">https://medium.com/p/171fd93b9d4b</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Szymon Kosno]]></dc:creator>
            <pubDate>Sun, 25 Oct 2015 19:36:05 GMT</pubDate>
            <atom:updated>2015-11-03T17:55:21.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*vNhaw1SCSu_DuKwSHZSQnQ.png" /></figure><p>Few days ago we all had opportunity to learn a lot of new things about Angular 1 and 2 with Angular Connect 2015 (if you haven’t checked it, <a href="https://www.youtube.com/channel/UCzrskTiT_ObAk3xBkVxMz5g">I urge you to view recordings here</a>). There are many new features that soon (hopefully)will be available for developers. In the meantime it is good to look back at what we might have missed in a stack we are currently using.</p><p>This time I will focus on features made available around version 1.0 — 1.3 (part 1 and <a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-2-3a40b8c7270e">part 2</a>). I will follow up in another post focusing on changes introduced somewhere between 1.3–1.4.</p><p>DISCLAIMER! This is not a change log or tutorial — it is just a list of features that might have been overlooked when working with Angular.</p><h3>What features were introduced?</h3><ol><li><strong>You can use ternary operator for assignments in expressions</strong></li></ol><pre>scope.$eval(‘a = 1 ? 2 : 3’);<br>expect(scope.a).toBe(2);</pre><pre>scope.$eval(‘0 ? a = 2 : a = 3’);<br>expect(scope.a).toBe(3);</pre><pre>scope.$eval(‘1 ? a = 2 : a = 3’);<br>expect(scope.a).toBe(2);</pre><p><strong>2. There is „$submitted, $touched, $untouched” parameter available in form controller as well as “$setSubmitted(), $setUntouched()” and on ngModel “$setTouched()”</strong></p><p><strong>3. Default directive restriction is now „EA” instead of „A”</strong></p><p><strong>4. $q can be used in streamlined version</strong></p><pre>$q(function(resolve, reject) { resolve(data); })</pre><p><strong>5. You can make multiline directives (like ng-repeat-start and -end) but there is a special property “multiElement: true”</strong></p><p><strong>6. You can escape interpolation with “\\”</strong></p><pre>\\{\\{foo\\}\\}</pre><p><strong>7. ngRepeat can alias result if there is a filter applied on array repeated so that the result set can be referred in the loop</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/247429b77f82e6b5ae6df61689f4e4d8/href">https://medium.com/media/247429b77f82e6b5ae6df61689f4e4d8/href</a></iframe><p><strong>8. You can bind ng-model to getter/setter function</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1100aaf67cfa3fd0dc3c57cdea36a21a/href">https://medium.com/media/1100aaf67cfa3fd0dc3c57cdea36a21a/href</a></iframe><p><strong>9. You can force all pending model updates to be immediately executed</strong></p><p>When working with forms you can happen to click “submit” button before models are really updated (because of things like debounce option or similar). In such case there is a form method <strong>$commitViewValue </strong>that will immediately commit all pending updates to model</p><p>IMPORTANT: when you handle form submit through “ng-submit” action, this is done automatically. In case of “ng-click” it has to be done manually.</p><p><strong>10. There is “strict-di” mode available that will make sure code is ready for production builds (uglify etc.)</strong></p><pre>angular.bootstrap(document, [“name”], {<br>  strictDi: true<strong><br></strong>});</pre><pre>OR</pre><pre>&lt;html ng-app=”name” ng-strict-di&gt;<br>  <em>&lt;!-- </em>… --&gt;<em><br></em>&lt;/html&gt;</pre><p><strong>11. You can modify ng-model behaviour by passing to ng-model-options configuration object</strong></p><ul><li>updateOn: string specifying which event should the input be bound to. You can set several events using an space delimited list. There is a special event called default that matches the default events belonging of the control, e.g. ng-model-options=“{ updateOn: ‘default blur’ }</li><li>debounce: integer value which contains the debounce model update value in milliseconds. A value of 0 triggers an immediate update. If an object is supplied instead, you can specify a custom value for each event. For example: ng-model-options=“{ debounce: { ‘default’: 500, ‘blur’: 0 } }”</li><li>allowInvalid: boolean value which indicates that the model can be set with values that did not validate correctly instead of the default behavior of setting the model to undefined.</li><li>getterSetter: boolean value which determines whether or not to treat functions bound to ngModel as getters/setters.</li></ul><p><strong>12. $observe now returns de-registration function like $watch</strong></p><p><strong>13. You can register controllers, services and filters by passing map instead of standard (‘name’, function) pair (can be useful with require etc.)</strong></p><pre>.controller({<br>name1: function1,<br>name2: function2});</pre><p><strong>14. Forms support expressions as form names. This means you can bind form to controller instance</strong></p><pre>&lt;form name=”ctrl.form”&gt;<br>...</pre><pre>function YourController () {<br>  this.form; //form is available on &quot;this&quot; in controller<br>}</pre><p><strong>15. You can disable debug mode (no classes like ng-scope) for production app (aprox. 10% faster)</strong></p><pre>myApp.config([‘$compileProvider’, function ($compileProvider) {<br>  $compileProvider.debugInfoEnabled(false);<br>}]);</pre><p>But you can always reload application again in debug mode (e.g. on production incident debug)</p><pre>angular.reloadWithDebugInfo();</pre><p><strong>16. You can (and should) bind isolated scope attributes directly into controller instance instead of scope when using “controllerAs” syntax</strong></p><pre>scope: {<br>  &#39;myData&#39;: &#39;=someData&#39;,<br>  &#39;myString&#39;: &#39;@someInterpolation&#39;,<br>  &#39;myExpr&#39;: &#39;&amp;someExpr&#39;<br>},<br>controllerAs: “someCtrl”,<br>bindtoController: true</pre><p><strong>17. You can coalesce calls to $apply for $http responses which occur close together (so that only one $digest is there)</strong></p><pre>angular.module(‘myFancyApp’, []).<br>config([&#39;$httpProvider&#39;, function($httpProvider) {<br>  $httpProvider.<strong>useApplyAsync</strong>(true);<br>});</pre><pre>OR:</pre><pre>angular.mock.module(function($httpProvider) {<br>  $httpProvider.<strong>useApplyAsync</strong>(true);<br>});</pre><p><strong>18. You can coalesce in fact any call to $apply by using $applyAsync instead</strong></p><p>NOTE: Within the $digest, $applyAsync() will only flush if the current scope is the $rootScope. This means that if you call $digest on a child scope, it will not implicitly flush the $applyAsync() queue. <a href="http://www.bennadel.com/blog/2751-scope-applyasync-vs-scope-evalasync-in-angularjs-1-3.htm">http://www.bennadel.com/blog/2751-scope-applyasync-vs-scope-evalasync-in-angularjs-1-3.htm</a></p><p><strong>19. You can request download of template (and storying it in $templateCache) using new $templateRequest service</strong></p><p><a href="https://docs.angularjs.org/api/ng/service/$templateRequest">AngularJS</a></p><p><strong>20. Date filter can be passed third parameter “UTC” to parse date against UTC instead of browser time zone</strong></p><p><strong>21. input ngModelOptions accepts timezone setting</strong></p><p>timezone: Defines the timezone to be used to read/write the Date instance in the model for &lt;input type=”date”&gt;, &lt;input type=”time”&gt;, … . It understands UTC/GMT and the continental US time zone abbreviations</p><p><strong>22. “filter” filter is now passing index to function predicate (so you can make filtering function based on index)</strong></p><p><strong>23. You can use interpolated values in “name” attribute on form elements</strong></p><pre>&lt;input type=”text” ng-model=”name” name=”name{{nameID}}” /&gt;</pre><p><strong>24. You can specify what type of document is template loaded by directive by specifying “templateNamespace” to one of “html, svg, math”</strong></p><p><strong>25. You can target “only parent” elements when requiring directive controllers</strong></p><pre>require: &#39;^^ngModel&#39;<br>require: &#39;?^^ngModel&#39;</pre><h3>See you next time — end of part 1</h3><p>That’s all for today, hope you have found something interesting in this list. As always I urge you to read full AngularJS change log to always be up-to-date:</p><p><a href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md">angular/angular.js</a></p><p>This post is now continued with “<a href="https://medium.com/@skosno/angularjs-did-you-know-from-1-0-to-1-3-part-2-3a40b8c7270e">AngularJS: Did you know…? From 1.0 to 1.3, part 2</a>”:</p><p><a href="https://medium.com/p/3a40b8c7270e"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=171fd93b9d4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AngularJS: API Error codes handing in Forms]]></title>
            <link>https://medium.com/@skosno/server-error-handing-in-angularjs-forms-c5fd38ccf0fc?source=rss-b283b097ae18------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5fd38ccf0fc</guid>
            <category><![CDATA[error]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Szymon Kosno]]></dc:creator>
            <pubDate>Sun, 17 May 2015 17:30:16 GMT</pubDate>
            <atom:updated>2015-05-20T16:12:13.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>AngularJS: API Error codes handling in Forms</h3><h4>TL;DR</h4><p>Do not handle error codes in controller. Use directive to handle API errors as you would use standard Angular validators:</p><p><a href="http://plnkr.co/edit/19cZ1WYRKOvZlSVSaDXb?p=preview">http://plnkr.co/edit/19cZ1WYRKOvZlSVSaDXb?p=preview</a></p><p>Lately I have been creating a lot of forms — administration applications just tend to have plenty of them. Obviously one of the most important topics I needed to solve is how to efficiently handle whatever server has to say about my beautiful model that I am sending to that beast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*faqmUQ0WyPxKY7AfkBz3LA.png" /><figcaption>Simple API error handling with global error and field error visible</figcaption></figure><p>Angular is great with forms having all those custom directives to handle validation and ng-messages to show errors as they come in (although lately I personally use custom directive based on ng-messages). But at some point you need to send all of that data to the server and a lot of bad things can happen. Depending on your application you can have 100% of server side validation replicated on Frontend, which is great, but often there are some checks that will be done just when you send the whole thing. Whatever is the case, your API will eventually send you a “not 200&quot; response that you need to handle. More importantly, you need to give user feedback what happened.</p><h4>Requirements</h4><p>When planning for api error handling I decided that I need to cover several use cases:</p><ol><li>I need to show general api errors in given place in form (e.g. top of the form). This is when something happens and we don’t really know what (server failed)</li><li>I need to show field related error next to the field as I would show standard validation error.</li><li>I need to show some errors in general area that are field related but that field is not found in form.</li><li>I want to be able to decide if particular form field should have error attached to that field or should it fall into “general error” area.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*QESD3FVwgr7fZ3-B8Kl_SQ.png" /><figcaption>Use Case 1 and Use Case 2 for simple API error handling</figcaption></figure><p>I believe 1 and 2 are easy to understand but some explanation is needed for number 3 and 4.</p><p>Why number 3? Sometimes you are adding some data to request that is not explicitly editable by user inside form (hidden fields, some generated data). It can happen that this additional data is invalid. In such case we need to tell something meaningful to the user. Even if it is to contact administrator etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*Y51LqF0k1fi-YiP4W7sc4Q.png" /><figcaption>Use Case 3 and Use Case 4 for simple error handling</figcaption></figure><p>Why 4? This might be my custom requirement but I needed to be able to decide if particular form field is considered an “API field” and should get all errors delivered to that field $error. This solution assumes that field need to be consciously declared as “aware of api errors” to get those delivered.</p><h4>Form validation and API errors</h4><p>Frontend validators are cool. We know what happens, we know how to fix it. Angular comes in and gives us all those helpers like $valid, $invalid etc. But it is not so easy when handling API error. We do not necessarily know what is the reason error occurred just from response and we are not prepared to call any validation mechanism that could tell us when it got fixed. Error happened, user should read the message and act accordingly. We will just try not to get in user’s way.</p><p>To enable that we definitely do not want to block re-sending the form if we cannot say when user fixed issue. For that reason let’s divide API errors into 2 groups:</p><ol><li>Do not invalidate form at all (save button should be enabled)— use cases 1, 2 and 4</li><li>Invalidate one field model (save button gets disabled)— use case 3</li></ol><p>What it means is that if there is any type of general error not connected to any form field or the field is not found in form or not marked as “API error aware”, do not invalidate anything. If there is an API error for existing field and that field tells us that it wants to handle API errors, then apply that error to the field resulting in $invalid state for field model.</p><p>Direct result of those requirements is the need to implement proper mechanism to take in API error connected to the field and then remove it as user attempts to fix this error.</p><h4>Planning solution</h4><p>If you create a simple AngularJS application you might have created a controller that exposes function like “ctrl.save()” that sends the data and possibly handles error in promise failure block like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f790bfd4ab003464f75489e0c7fbd4a/href">https://medium.com/media/4f790bfd4ab003464f75489e0c7fbd4a/href</a></iframe><p>This works ok for small applications but we need something more complex and a bit more automated and obvious from HTML perspective. For this we create following components:</p><ol><li>api-form directive — it should be declared next to “form” or “ng-form” and will automatically attach logic to that form controller.</li><li>api-validate directive — it should be declared next to ng-model on particular field to indicate that this field is “server error aware”. Plus it will hold logic on when to remove error. It will expose “$registerApiError” interface on ng-model to handle API errors related with the field.</li><li>ApiFormValidationService — service used to implement all the logic needed by this solution.</li></ol><p>The goal is that by just adding “api-form” to any of our forms it will automatically start handling errors for us:</p><pre>&lt;form name=&quot;myForm&quot; api-form&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;fieldName&quot; ng-model=&quot;fieldModel&quot;/&gt;<br>&lt;/form&gt;</pre><p>To have an error attached to the field errors, we just add api-validate directive next to it’s ng-model:</p><pre>&lt;form name=&quot;myForm&quot; api-form&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;fieldName&quot; ng-model=&quot;fieldModel&quot; api-validate/&gt;<br>&lt;/form&gt;</pre><p>Of course we need to be able to show general errors for my form so I need to extend formController with some custom parameters — we will add $api object to it. This object will hold basic information similar to the form itself but exposing what backend knows about this form. All fields in this object should work similarly how you expect them to work in standard form:</p><pre>$api: {<br>  $valid: true,<br>  $invalid: false,<br>  $error: null<br>}</pre><p>For the sake of this post let’s assume that backend is responding with this kind of structures when having error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dad28c639dfd6a7e86305437824d261/href">https://medium.com/media/3dad28c639dfd6a7e86305437824d261/href</a></iframe><h3>Implementation</h3><p>Now that the general idea is there, it is time to prepare some the actual code to do the job.</p><h4>API form validation service</h4><p>First we will implement the service that will abstract most of the code responsible for parsing errors, applying them to form and field error handlers.</p><p>In the most basic form we expect service to expose:</p><ul><li>reset(form) — simply reset current form “$api” object to it’s initial state;</li><li>setInvalid(form) — set $api form state to invalid form state; used when there is an API error not handled by field;</li><li>setValid(form) — set $api form state to valid form state; can be used to force API state to “valid” state;</li><li>applyError(form, error) — apply single error to given form; it checks if form field exist and has special “$registerApiError” interface exposed by field to know if error handling can be done by field itself;</li><li>applyErrors(form, reason) — parse API rejection reason and apply errors to form; used to handle rejected API communication;</li></ul><p>Taking that into account we can create a factory service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1acbe660d85b7199a7c32fe8cb54d1d5/href">https://medium.com/media/1acbe660d85b7199a7c32fe8cb54d1d5/href</a></iframe><h4>API validate directive</h4><p>This validation mechanism requires that there can be a special end point “$registerApiError” exposed on field’s ng-model so that individual field error can be passed there and handled by user interacting with the field directly. This kind of handler enables us to show API error next to the field itself similarly as other UI validators.</p><p>Once user interacts with the field model we want to get rid of any API error related with that field. We do not really know when user fixes error properly so we provide just a “dumb” functionality to remove all API errors once validation loop kicks in for the field.</p><p>Our field validation directive could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70384035401b033ab6f284b2c534e34a/href">https://medium.com/media/70384035401b033ab6f284b2c534e34a/href</a></iframe><h4>API form directive</h4><p>Final piece required for this mechanism. This is the part that connects our service and field directive to provide full functionality. It should be added to “form” or “ng-form” HTML element.</p><p>For this directive to work, we need to know when form got submitted and more importantly when the request got resolved or rejected. In this post I will simply require that request promise is given directly as “api-form” input that we can watch. We might want to later on try include automatic form submission capture if needed.</p><p>How we want this directive to work is:</p><ol><li>Check if there is “form” or “ngForm” controller defined on element;</li><li>Watch “api-form” attribute for value changes, once change detected try to handle it as request promise;</li><li>Register request success handler, resetting form API state;</li><li>Register request failure handler, forwarding handling and error application to API form service;</li></ol><p>Code implementation could look something like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bfdc5b2fa8de20322152d9d1a560df1/href">https://medium.com/media/2bfdc5b2fa8de20322152d9d1a560df1/href</a></iframe><h3>Conclusion</h3><p>With those three pieces in place we can now simply use this mechanism to discard custom Controller error handling code and just pass promise that is returned by our request.</p><p>New Controller could look something like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a6f37b74906b091e3d495c0fd257188/href">https://medium.com/media/5a6f37b74906b091e3d495c0fd257188/href</a></iframe><p>Using it as directive:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d13ae1d8869fd75934b07660cf9f4922/href">https://medium.com/media/d13ae1d8869fd75934b07660cf9f4922/href</a></iframe><p>And inside HTML:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36c21f6c934fa1d7767c5618fe52cf9/href">https://medium.com/media/e36c21f6c934fa1d7767c5618fe52cf9/href</a></iframe><p>What about additional data returned with request or full validation messages inside response? Hopefully in next part.</p><h4>Live demo</h4><p>What is a blog post without a demo? So here you are, hope you enjoyed!</p><p><a href="http://plnkr.co/edit/19cZ1WYRKOvZlSVSaDXb?p=preview">http://plnkr.co/edit/19cZ1WYRKOvZlSVSaDXb?p=preview</a></p><p><a href="http://embed.plnkr.co/19cZ1WYRKOvZlSVSaDXb/preview">Plunker - AngularJS: API Error Handing in Forms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5fd38ccf0fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>