genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

Tricky Angular 1 concepts explained #141

Open genkio opened 7 years ago

genkio commented 7 years ago

A list of tricky angular 1 concepts, and the best explanations I found.

What's the differences between ngModel formatter and parsers? source

//format text going to user (model to view)
ngModel.$formatters.push(function(value) {
  return value.toUpperCase();
});

//format text from the user (view to model)
ngModel.$parsers.push(function(value) {
  return value.toLowerCase();
});

What does require: 'ngModel' do? source

myApp.directive('myDirective', function($timeout) {
  return {
    restrict: 'EA',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
        ngModel.$render = function() {
            $timeout(function() {
                ngModel.$setViewValue('StackOverflow');  
            }, 5000);                
        };
    }
  };
});

What does ng-transclude do? source

angular.module('app', [])
  .directive('hero', function () {
    return {
      restrict: 'E',
      transclude: true,
      scope: { name:'@' },
      template: '<div>' +
                  '<div>{{name}}</div><br>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
  });

// <hero name="superman">Stuff inside the custom directive</hero>

What does controllerAs and bindToController do?

angular.directive('userStatus', function() {
  return {
    restrict: 'E',
    template: '<span><i ng-class="us.iconCss()"></i> {{ us.user.status }}</span>',
    scope: {
      user: '='
    },
    controllerAs: "us",
    bindToController: true,
    controller: function() {
      var vm = this;
      vm.iconCss = function() {
        return vm.user.status === "enabled" ? 
          "fa fa-check" : "fa fa-times";
      };
    }
  };
});

Should business logic go into controller or link function in custom direcgives? source

var linker = function(scope, element, attrs){
  element.on('click', scope.someFunctionDefinedInTheControllerFunction); 
}; 

Why $scope.obj.data is better than $scope.data source