unable to pass parameter to angular directive

你离开我真会死。 提交于 2019-12-13 04:38:49

问题


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.



来源:https://stackoverflow.com/questions/32187385/unable-to-pass-parameter-to-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!