1

「ui_select2」ディレクティブでangularjsを使用しています。Select2 は書式設定機能を使用して新しいタグを描画します。「ng-click」属性を持つ「」要素があります。新しいDOM要素についてangularjsに伝える方法は? そうしないと、新しい「ng-clicks」が機能しません。

HTML:

<input type="text" name="contact_ids" ui-select2="unit.participantsOptions" ng-model="unit.contactIds" />

JS (角度コントローラー):

anyFunction = function(id) {
    console.log(id)
}

formatContactSelection = function(state) {
    return "<a class=\"select2-search-choice-favorite\" tabindex=\"-1\" href=\"\" ng-click=\"anyFunction(state.id)\"></a>"
}

return $scope.unit.participantsOptions = {
    tags: [],
    formatSelection: formatContactSelection,
    escapeMarkup: function(m) {
        return m
    },
    ajax: {
        url: '/contacts/search',
        quietMillis: 100,
        data: function(term, page) {
            return {
                term: term,
                limit: 20,
                page: page
            }
        },
        results: function(data, page) {
            return {
                results: data,
                more: (page * 10) < data.total
            }
        }
    }

}

問題は、select2 が angularjs によってまだ発見されていない DOM 要素を作成することです。angularjs $compile 関数を使用して新しい DOM 要素をいくつかの要素に追加する必要があることを読みましたが、コントローラーでは使用できません。

4

1 に答える 1

1

解決策を見つけました - ngModel の変更を監視し、既に ui_select2 ディレクティブを持っている要素に適用するディレクティブを作成しました。「uiRequiredTags」は、select2 タグの選択に必要なカスタム動作を実装します。解決策は、ngModel 属性の変更を監視することです。

angular.module("myAppModule", []).directive("uiRequiredTags", function() {
    return {
        restrict: 'A',
        require: "ngModel",
        link: function(scope, el, attrs) {
            var opts;
            opts = scope.$eval("{" + attrs.uiRequiredTags + "}");
            return scope.$watch(attrs.ngModel, function(val) {
                var $requireLink;
                $requireLink = el.parent().find(opts.path);
                $requireLink.off('click');
                $requireLink.on('click', function() {
                    var id, n, tagIds;
                    id = "" + ($(this).data('requiredTagId'));
                    if (opts.removeLinkPath && opts.innerContainer) {
                    $(this).parents(opts.innerContainer).find(opts.removeLinkPath).data('requiredTagId', id);
                }
                tagIds = scope.$eval(opts.model).split(',');
                n = tagIds.indexOf(id);
                if (n < 0) {
                    tagIds.push(id);
                } else {
                    tagIds.splice(n, 1);
                }
                scope.$eval("" + opts.model + " = '" + tagIds + "'");
                scope.$apply();
                return $(this).toggleClass('active');
            });

        });
    }
};
于 2013-11-08T17:26:47.237 に答える