【问题标题】:Dynamically changing directive attributes in AngularJsAngularJs 中动态改变指令属性
【发布时间】:2015-10-05 20:12:58
【问题描述】:

需要一些帮助才能完成它。但如果有人有更好的建议,我是一个思想开放的人。

基本上我已经编写了一个指令来根据指令属性交换模板。

<div id="popup" class="popup my-directive" type="player" style="display: none;"></div>

我遇到的问题是更改 type 属性,使其触发 $digest 并重新评估我的指令。

$scope.selectTeam = function () {
    $scope.type = 'team';
    //$scope.$apply(function () {
    // bind directive
    $(".popup").attr("type", "team");
    // show popup div
    $(".popup").show();
    //});
};

type 属性的目的是跟踪哪个模板将绑定到popup div。

app.directive('myDirective', function () {
    return {
        restrict: 'AEC', // Attribute, Element, Class
        transclude: true, // expose controller scope
        templateUrl: function(element, attr){
            var type = typeof attr.type !== 'undefined' ? attr.type : 'player';

            if(!type) return;

            return 'search-' + type + '-tpl.html';
        },
    }
});

如需现场示例,请查看我的plunker

我现在将尝试使用$compile 在每个选择函数中使用新的type 值构建我的popup,但我真的不喜欢这种方法。

更新

好的,我破解它的速度比最初预期的要快。直播plunker

我对控制器的改动:

$scope.selectTeam = function () {
    $scope.type = 'team'; // trigers $digest
    $(".popup").replaceWith($compile(angular.element(document).find("my-directive").attr("type", "team"))($scope));
    $(".popup").show();
};

我对 HTML 所做的更改:

<my-directive id="popup" class="popup" type="player" style="display: none;"></my-directive>

当我尝试搜索时,我注意到的唯一问题是Cannot read property 'insertBefore' of null。但我可以忍受这个。

正如我之前提到的,如果有人有不同的想法/方法或注意到我的代码中有一些有趣的地方,请分享。

【问题讨论】:

  • 我会试试看我能做什么。但在我看来,这真的太复杂了。大多数时候自定义指令被误用,可以在没有指令的情况下简单地解决。你能提供更多关于你想要做什么的细节吗? (功能上,而不是技术上)。
  • 好吧,进一步看看你的代码,我能猜到你为什么会遇到一些复杂的问题。您在角度控制器中使用了一些 jQuery。你永远不应该那样做。我们可以在这里聊聊chat.stackoverflow.com/rooms/83430/… 吗?
  • @Okazari 我当然同意你的观点。我正在尝试提供一种弹出机制,用于从something 的集合中搜索和选择一个值。根据 something 的搜索内容,值可能会有所不同。这就是为什么我在废弃我的$compile 版本-plnkr.co/edit/JKOYHMdaarUrl4R11dKm?p=preview 之后使用指令。虽然我在我的 plunkers 中使用了非常简单的示例,但实际上这些搜索/选择弹出窗口会更加复杂。我希望这能提供一些见解。

标签: angularjs templates binding angularjs-directive


【解决方案1】:

经过一番交谈,我找到了两个解决方案。

首先,您可以通过这种方式使用 ng-include 来做您需要的事情,而不是创建自定义指令(参见 plunker):

<div ng-show="showSelect" ng-include="'search-'+type+'-tpl.html'">

其次,我指出这可能是使用来自 ui-boostrap 的 $modal(使用“templateUrl”)的模态。

我实际上更喜欢第二个选项,因为您可以为每个模态定义一个控制器、模板、css 等,这更简洁易读。

【讨论】:

  • 非常感谢您与我聊天。我从中学到了很多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多