rossoneri rossoneri - 1 year ago 117
AngularJS Question

how to get access to controller scope when testing directive with isolate scope

I have directive with isolate scope and controller, Is it right to write unit tests for directive and test some functional in controller scope?

And if it right, how i can get access to controller scope?

angular.module('myApp').directive('myDirecive', function () {
return {
templateUrl: 'template.html',
scope: {
data: '='

controller: function ($scope) {
$scope.f= function () {
$scope.value = true;

link: function ($scope) {
// some logic

describe('myDirective', function () {
'use strict';

var element,


beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();

element = compileElement();

function compileElement() {
var element = angular.element('<my-directive></my-directive>');
var compiledElement = $compile(element)($scope);


return compiledElement;

it('should execute f', function () {
expect($scope.val).toBe(true); // there we can access to isolate scope from directive;

Answer Source

Controller is given the isolated scope created by the directive. Your $scope, that you pass into compile function, is used as a parent for the directive's isolate scope.

Answering how to test it, you have two options:

  1. Access the isolated scope from the element:

    var isolated = element.isolateScope();

    For that, you need to have $compileProvider.debugInfoEnabled(true);

  2. Access the isolated scope from your scope:

    var isolated = $scope.childHead;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download