简体   繁体   中英

Controller's scope is undefined after compiling a directive with $compile

I'm writing an unit test for this directive:

.directive('readOnlyExplorer', () => ({
  templateUrl:
    'components/experiment-explorer/read-only-explorer.template.html',
  restrict: 'E',
  controller: 'ReadOnlyExplorerController',
  controllerAs: 'vm',
  scope: {
    extensionRegExp: '@?',
    foldersRegExp: '@?',
  },
  bindToController: true
}))

As you can see, I'm using controllerAs and an isolate scope to pass arguments to the directive. The controller is class based.

Everything works except for unit test. What I'm doing is to compile the directive and then trying to access the scope. This is the code of the unit test:

element = $compile(
  '<read-only-explorer extension-reg-exp="csv" folders-reg-exp="csv"></read-only-explorer>')($rootScope);
$rootScope.$digest();
const controller = element.scope().vm;
console.log(controller.foldersRegExp) // isolate scope variable, it is undefined
console.log(controller.loadFolder) // controller method, it is undefined

The problem is that neither scope() nor vm contain the scope I want to access. vm is actually undefined. Why is this happening? I guess I'm not using $compile correctly.

The controller is on the isolate scope of the element: 1

element = $compile(
  '<read-only-explorer extension-reg-exp="csv" folders-reg-exp="csv"></read-only-explorer>')($rootScope);
$rootScope.$digest();
̶c̶o̶n̶s̶t̶ ̶c̶o̶n̶t̶r̶o̶l̶l̶e̶r̶ ̶=̶ ̶e̶l̶e̶m̶e̶n̶t̶.̶s̶c̶o̶p̶e̶(̶)̶.̶v̶m̶;̶
const controller = element.isolateScope().vm;
console.log(controller.foldersRegExp) // isolate scope variable
console.log(controller.loadFolder) // controller method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM