• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • Angularjs tips

    Blogs20142014-12-20


    Some Angularjs tips

    1. $resource and $promise: The following are equivalent:
    var todo = Todo.get({id: 123}, function() {
       $scope.todo = todo;
    });
    
    Todo.get({id: 123}, function(todo) {
       $scope.todo = todo;
    });
    
    Todo.get({id: 123}).$promise.then(function(todo) {
       $scope.todo = todo;
    });
    
    var todo = Todo.get({id: 123});
    todo.$promise.then(function() {
       $scope.todo = todo;
    });
    2. angular.element===jQuery

    If jQuery is available, angular.element is an alias for the jQuery / $ function. If jQuery is not available, angular.element delegates to Angular’s built-in subset of jQuery, called “jQuery lite” or “jqLite.“:

    var el = document.querySelector( 'div.special' );
    var $el = angular.element( el );
    
    //delete an item in angular array, use the array's splice and indexOf methods:
    $scope.persons.splice( $scope.persons.indexOf(person), 1 );
    //or underscore way:
    //1. _.without()
    scope.newNodes = _.without($scope.nodes, _.findWhere($scope.nodes,
      {name: res}));
    
    //2. _filter:
    $scope.newNodes = _.filter($scope.nodes, function(node) {
      return !(node.name == res); });
    
    //among many ways to prevent event click default:
    <a href ng-click="doSomething(); $event.preventDefault();
      $event.stopPropagation();">An safe Click.</a>
    // a directive way:
    app.directive('a', [function() {
      return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
          elem.bind('click', function(e){
            if (attrs.ngClick||attrs.href === ''||attrs.href == '#'){
              e.preventDefault();
              e.stopPropagation();
            }
          })
        }
      };
    }])