unable to pass parameter to angular directive

2019-09-12 12:07发布

问题:

I want to initiate a third party control (bootstrap-select) after a collection has been assigned to a source variable. For that I am using a directive and watching a collection like this.

angular
.module('app').directive('bootstrapDropdown', ['$timeout',
    function ($timeout) {
        return {
            restrict: 'A',
            scope: {
                collectionName: '='
            },
            require: '?ngModel',
            link: function (scope, el, attrs) {
                el.selectpicker();
                scope.$watchCollection(scope.collectionName, function (newVal) {
                    $timeout(
                        function () {
                            el.selectpicker('refresh');
                        }
                    );
                });
            }
        };
    }
]);

If I pass the name of collection as string in $watchCollection it works fine. But I am looking for a generic directive so I am passing name of collection like

   <select bootstrap-dropdown collection-name="commandGroups"  ng-model="vm.Job.CommandGroup" name="ddlCommandGroup">
                        <option value="">Select Something</option>
                        <option ng-repeat="cmdGroup in commandGroups" collection-name="commandGroups" value="{{cmdGroup.Id}}">{{cmdGroup.Name}}</option>
                    </select>

But it's not working

回答1:

Collection-name is an attribute on the select-element and can't just be watched by using scope.collectionName since that will return undefined. You can get the value from the 'collection-name' attribute by using the following line in your link-function:

scope.collectionName = attrs.collectionName;

Not sure if it works for you since I have no data, but it probably helps you further.