angular.bind()

by Richard Hunter

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
<h2>angular.bind()</h2>

JavaScript

(function() {
    
    'use strict';
    
    //  demonstrating partial application
    function add(op1, op2) {
        return op1 + op2;
    }
    
    var  addToThree = angular.bind(null, add, 3);
    
    alert(addToThree(2));
    
    //  using bind to bind a function to a context
    var context = {
        name: 'Richard'
    }
    
    function foo() {
        console.log(this.name);
    }
    try {
        // this will throw an error since we are in strict mode
        foo();
    } catch(error) { console.error(error); }
    
    var foo2 = angular.bind(context, foo);
    //  this consoles out my name correctly
    foo2();
}());