Thursday, September 10, 2015

Angular mistakes (1.x)

Hello everyone, it's been a while. I had a lot of work to do, but now I got the time to post this collection I have been collecting. Enjoy!
  •  directive's attribute should be dashed, not camelCased, but in the scope of the directive it should be camelCased
    <list-display scroll-left="scrollLeft"></list-display>
    scope:{scrollLeft: "="}
    • very annoying thing..
  • inside a directive the function should be not declared like the "var"-y way
    function xy(){..}
    -- good
    var xy = function(){..} 
    - not good
  • Most of the bugs come from this mistake:
    you should be injecting via the array notation the dependencies, not like
    function ($scope){..}

    but
    ['$scope', function(scope){..}]

    This messes up the uglification --> arguments will be uglified, so Angular's compilation will not understand what you want to inject.
  • If you're defining a controller inside a directive, you have to be aware injecting dependencies, like '$element' and such. Better way is to define it on the module like this:
    angular.module("App").controller('SwiperController',['$element', function ($element) {..}]);
     angular.module("App").directive('someDirective', SwiperContainer)
    function SwiperContainer() {return {restrict: 'E',transclude: true,controller: 'directiveController',template: '<div class="swiper-container {{containerCls}}"><div class="swiper-wrapper" ng-transclude></div></div>'}}
  • ES6: if you're writing a service, the name of the class should start with a capital letter!
    var module = angular.module("TimelinexrClient");
    class DataService {
    constructor(http) {
    this.http = http;
    this.baseURL = "http://localhost:8080";
    }
    getPaths(from, to) {
    }
    }
    DataService.$inject = ['$http'];
    module.service('DataService',DataService);
    export default module;
  • DON'T START A DIRECTIVE ATTRIBUTE WITH x- OR data-! 
  • if you're using window's setTimeout function instead of $timeout service, you have to call in the end a $scoe.$apply (or $digest) function. 
    • The main reason here is Angular is not running the digest loop, so if you're making changes in the model, it will not be rendered to the view.
This list is not complete, there will be added more mistakes later on!