AngularJs 中动态更改指令属性

Dynamically changing directive attributes in AngularJs

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

基本上我写了一个指令来根据指令属性换出模板。

<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 在每个 select 函数中使用新的 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。但我可以忍受这个。

正如我之前提到的,如果有人有不同的 idea/approach 或发现我的代码中有一些有趣的地方,请分享。

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

首先,您可以通过这种方式使用 ng-include 来完成您需要的操作,而不是创建自定义指令(查看它在这个 plunker 中的工作):

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

其次,我指出这可能是使用来自 ui-boostrap.

的 $modal(使用“templateUrl”)的模式

我实际上倾向于选择第二个选项,因为您可以为每个模态定义一个控制器、模板、css 等...,这样更清晰易读。