如何在AngularJS中使用Bootstrap Multiselect Dropdown

Oc *_*Dau 20 twitter-bootstrap angularjs angular-ui angularjs-directive

我想在AngularJS中使用Bootstrap Multiselect Dropdown http://davidstutz.github.io/bootstrap-multiselect/.我听说有必要将其移至指令.但我认为这很复杂,不知道我该做什么.如果您有经验,请指导我!韩国社交协会.

Eth*_* Wu 16

这是我在项目中使用的指令.它适用于Chrome和Firefox.您可以根据自己的需要更改选项.

angular.module('yourApp')
.directive('yourDirective', function () {
    return {
        link: function (scope, element, attrs) {
            element.multiselect({
                buttonClass: 'btn',
                buttonWidth: 'auto',
                buttonContainer: '<div class="btn-group" />',
                maxHeight: false,
                buttonText: function(options) {
                    if (options.length == 0) {
                      return 'None selected <b class="caret"></b>';
                    }
                    else if (options.length > 3) {
                      return options.length + ' selected  <b class="caret"></b>';
                    }
                    else {
                      var selected = '';
                      options.each(function() {
                        selected += $(this).text() + ', ';
                      });
                      return selected.substr(0, selected.length -2) + ' <b class="caret"></b>';
                    }
                }
            });

            // Watch for any changes to the length of our select element
            scope.$watch(function () {
                return element[0].length;
            }, function () {
                element.multiselect('rebuild');
            });

            // Watch for any changes from outside the directive and refresh
            scope.$watch(attrs.ngModel, function () {
                element.multiselect('refresh');
            });

        }

    };
});
Run Code Online (Sandbox Code Playgroud)

更新处理AngularJS v1.3.15和bootstrap-multiselect v0.9.6的指令的两个片段:JavaScript,CoffeeScript


lau*_*ent 13

如果您不需要创建非常可重用的代码,那实际上并不复杂.第一步是创建一个基本指令并获取DOM元素:

angular.module('yourapp', [])

.directive('multiselectDropdown', [function() {
    return function(scope, element, attributes) {

        element = $(element[0]); // Get the element as a jQuery element

        // Below setup the dropdown:

        element.multiselect({
            option1: 123,
            option2: "abcd",
            // etc.
        })

        // Below maybe some additional setup
    }
}]);
Run Code Online (Sandbox Code Playgroud)

基本上,一旦你在指令内,它实际上只是常规的jQuery或JS代码.

然后在您的HTML代码中:

<select multiselectDropdown >
    <option value="1">One</option>
    <option value="2">One</option>
    <option value="3">One</option>
</select>
Run Code Online (Sandbox Code Playgroud)

您还可以在DIV上指定其他属性,并使用attributes指令的参数获取值.

  • 就像插件一样,这是你想要迁移到AngularJS的所有jquery插件的优秀模型.你的'multiselectDropdown'不应该是'multiselect-dropdown'吗? (7认同)