【问题标题】:Recompile directive based on external variable基于外部变量重新编译指令
【发布时间】:2016-02-03 23:17:51
【问题描述】:

目前我正在编写一个应用程序,是否有必要在某个变量发生更改后重新编译指令/模板。由于我目前正处于开发总体和 Angular 的早期阶段,因此我还没有成功完成它。

我的指令如下:

app.directive('slider',function($compile){
    return {
        restrict:'E',
        templateUrl: function(){
        if (tempMovies.length>0){
        $compile('Slider.html');
        return 'Slider.html';
        } else { return 'Placeholder.html';};
        }
    };
});

var tempMovies=[];
<slider></slider>

我使用的模板滑块来自https://github.com/ksachdeva/angular-swiper,它使用 tempMovies 数组来显示某些项目。我遇到的问题是,一旦你正常更新滑块,它就会崩溃,所以一旦我的 tempMovies 变量发生变化,我需要重新编译模板。

我正在考虑在 tempMovies 上使用 $watch 执行此操作,然后触发 Slider.html 的编译,但我不确定如何。

感谢各位提前提供的帮助,到目前为止,学习 Angular 一直很受欢迎。 :)

【问题讨论】:

  • 你的链接功能在哪里?

标签: javascript html angularjs cordova


【解决方案1】:

您可能希望将您的 tempMoves 变量传递到指令中:

app.directive('slider', function($compile) {
  restrict: 'E', 
  scope: { // pass the variable to your directive
    tempMoves: '='  
  }
  ...
}

// in the markup
<slider temp-moves="someVar"></slider>

然后在您的指令中,您可以将 $watch 应用于 tempMoves 变量:

app.directive('slider', function($compile) {
  ... 
  link: function(scope, el, attrs) {
    scope.$watch('tempMoves', function(newValue, oldValue) {
      if (newValue != oldValue) {
        // do your $compile here or whatever else it takes to reset the slider
      }
    }
  }
}

【讨论】:

  • 嗨,保罗,感谢您的快速回复。我认为你提到的正是我需要的东西。只是一件小事,在我传递“someVar”时的标记中,我想从我的角度 app.js 文件中传递一个变量。目前我正在使用&lt;slider temp-moves='{{someVar}}',但我的 $watch 函数似乎没有注意到那里的变化。你知道有什么解决办法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多