Skip to content

Instantly share code, notes, and snippets.

@marcj
Last active May 18, 2016 21:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcj/dda218b489cedc5cc3e8 to your computer and use it in GitHub Desktop.
Save marcj/dda218b489cedc5cc3e8 to your computer and use it in GitHub Desktop.
AngularJS Cheatsheet

AngularJS Cheatsheet

Pitfalls

Scope does not detect changes with whitespace at the end and beginning

A: You need to set ng-trim to false.

   <input ng-model="model.name" ng-trim="false />

Require parent controller with same name

A: You can't with require: '^sameDirectiveName', use element.parent() instead

.directive('sameDirectiveName', {
    link: function(scope, element, attributes) {
        var parentSameDirectiveNameController = element.parent().controller('sameDirectiveName');
        //or use this to find a parent which isn't directly the parent.
        var parentController;
        while (element.parent() && !(parentController = element.parent().controller('sameDirectiveName')));
    }
});

Potential typos

Promises

var deferred = $q.defer();

deffered.resolve();
deffered.reject();
deffered.notify();

return deferred.promise;

Write argument values

$scope.$apply(function(){
   $parse(attributes.name).assign($scope, 'newValue'); //attributes.name can be simple 'name' or more complex '$parent.model.name'.
});

//or hardcoded:
$scope.model.name = 'newValue';

//this won't work always as there's no property called 'model.name' for example:
$scope[attributes.name] = 'newValue';

// or if you're outside of angular's scope (like extern events)
$scope.$apply(function(){
    $scope.model.name = 'ddd';
});

Read argument values

//<element name="model.name" />

var name = $scope.$eval(attributes.name); // peter/test
//<element name="model.name" />

$scope.$watch(attributes.name, function(name){
    //name=peter/test
});
//<element name="{{model.name}}/test" />

var name = $interpolate(attributes.name)($scope); // peter/test

var name = $interpolate('{{model.name}}/test')($scope); // peter/test
//<element name="{{model.name}}/test" />

attributes.$observe('name', function(name){
    //name=peter/test
});

Events

Scope on destruct/destroy

$scope.$on("$destroy", function() {
    if (this.getName()) {
        delete $scope.parentForms[this.getName()];
    }
}.bind(this));

Scope Binding

{
   scope: {
     text: "@myText",
     twoWayBind: "=myTwoWayBind",
     oneWayBind: "&myOneWayBind"
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment