当延迟加载指令时,它永远不会运行

时间:2016-07-21 21:48:13

标签: javascript angularjs angularjs-directive

我正在尝试延迟加载指令。它被加载和定义,但它永远不会在html上运行。如何在延迟加载指令后运行指令?

 public function add()
    {
    $avadiary = $this->Avadiaries->newEntity();
        if ($this->request->is('post')) {
            $avadiary = $this->Avadiaries->patchEntity($avadiary, $this->request->data);
            $avadiary->user_id = $this->Auth->user('id');
            if ($this->Avadiaries->save($avadiary)) {
                $this->Flash->success(__('The avadiary has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The avadiary could not be saved. Please, try again.'));
            }
        }
    $alumnesGrups = $this->Avadiaries->AlumnesGrups->find('all', [
    'fields' => ['Alumnes.name'], 
    'contain' =>['Alumnes', 'Grups'], 
    'conditions' => ['Grups.id =' => 1], 
    'order' => ['Alumnes.name' => 'ASC']
    ]);
$this->set(compact('avadiary', 'alumnesGrups'));
        $this->set('_serialize', ['avadiary']);
    }

HTML:

.config(function ($compileProvider, routes, $provide) {

    //Lazy define
    $compileProvider.directive('myDirective', function ($rootScope, $location, $filter) {

        console.log( "This IS called" );

        return function (scope, element, attrs) {
          console.log( "This is NEVER called");
        }
    }
}

如果我不懒加载它,就会调用它。

编辑:这也不起作用:

<div my-directive></div>

1 个答案:

答案 0 :(得分:2)

  

如何在延迟加载指令后运行指令?

在HTML中使用ng-if指令。

  <body ng-app='test'>
    <h1>Hello Plunker!</h1>
    <div my-directive ng-if="defined"></div>
    <button ng-click="defineIt()">Define it</button><br>
  </body>

通过在指令延迟加载后将defined变量设置为true ng-if指令将使用$compile服务进行编译延迟加载指令。

DEMO on PLNKR