<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body ng-app="app" ng-controller="BaseController">
<h1><span ng-bind="pageTitle"></span></h1>
<br/>
2 + 3 =
<span ng-bind="add(2,3)"></span>
<br/>
5 - 3 =
<span ng-bind="sub(5,3)"></span> <!-- This will not work since its not binded to scope -->
<br/><br/>
<br/><br/><br/><br/>
<br/><br/>
<!-- Add Jasmine -->
<script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine.js"></script>
<!-- Jasmine html & css for reporting -->
<link data-require="jasmine@*" data-semver="2.0.0" rel="stylesheet" href="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine.css" />
<script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine-html.js"></script>
<script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/boot.js"></script>
<!-- Add AngularJS -->
<script data-require="angular.js@1.2.25" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
<!-- AngularJS testing helpers -->
<script data-require="angular-mocks@*" data-semver="1.2.16" src="https://code.angularjs.org/1.2.16/angular-mocks.js"></script>
<script src="script.js"></script>
<script src="spec.js"></script>
</body>
</html>
// Code goes here
var app = angular.module("app", []);
app.controller("BaseController", function($scope) {
var title = "AngularJS Bind Example";
$scope.pageTitle = angular.bind(this, title);
var add = function(a, b) {
return a+b;
};
$scope.add = angular.bind(this, add);
//This will not work, since its not binded to scope.
var sub = function(a, b) {
return a-b;
}
});
/* Styles go here */
Angular.Bind
This is used to bind javascript functions to angular scope.
Syntax:
angular.bind(self, fn, args);
describe('Testing BaseController', function() {
var $scope = null;
var ctrl = null;
//you need to indicate your module in a test
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('BaseController', {
$scope: $scope
});
}));
it('should set title', function() {
var title = "AngularJS Bind Example";
$scope.appTitle = angular.bind(this, title);
expect($scope.appTitle).toEqual('AngularJS Bind Example');
});
it('should bind sum function to scope', function() {
var add = function(a, b) {
return a+b;
};
$scope.add = angular.bind(this, add);
expect($scope.add(2,3)).toEqual(5);
});
});