如何从指令到控制器获取索引

时间:2015-04-28 18:35:18

标签: angularjs angularjs-directive

如何从指令获取index值到控制器。 我尝试了但是我在指令处获得索引但是当我将它传递给控制器​​时我需要将它传递给控制器​​,我得到了未定义。

请帮帮我, 提前谢谢。

指令html

<li class="tag" ng-repeat="lists in list" ng-if="lists.userName">
  <span class="tag-label">{{lists.userName}}</span><span class="tag-cross pointer" ng-click="delete($index,'people', list);">x</span>
</li>

directive.js

.directive('search', function ($timeout) {
    return {
        restrict: 'AEC',
        scope: {
            items: '=',
            listitem: '=',
            prompt: '@',
            title: '@',
            subtitle: '@',
            model: '=',
            list: '=',
            onSelectupdate: '&',
            onDelete: '&',
            index: '='


        },
        link: function (scope, elem, attrs, index) {
            scope.handleSelection = function (selectedItem) {
                scope.model = selectedItem;
                console.warn(scope.model);
                console.warn(scope.items);
                console.warn(scope.model);
//                scope.searchModel = selectedItem.displayConfig[0].propertyValue;
                console.warn(scope.items);
                console.warn(scope.model);
                scope.current = 0;
                scope.selected = true;
                $timeout(function () {
                    scope.onSelectupdate();

                }, 200);
            };
            scope.delete = function (index) {
                alert('index'+index);
                var index= index;
                $timeout(function () {
                    scope.onDelete();

                }, 200);
            };

            scope.$watch("items", function (newData) {
                console.log("Items: ", newData);
            });
            scope.current = 0;
            scope.selected = true;
            scope.isCurrent = function (index) {
                return scope.current == index;
            };
            scope.setCurrent = function (index) {
                scope.current = index;
            };
        },
        templateUrl: TAPPLENT_CONFIG.HTML_ENDPOINT[0] + 'home/genericsearch.html'
    }
})

controller.js

$scope.removeRecipient = function (index, type, data) {
        console.warn(type);
        alert("index"+index)
        if (type == 'orgs') {
            $scope.recipientsOrg.splice(index, 1);
            $scope.recipientsOrgIdArr.splice(index, 1);
        } else if (type == 'people') {
            $scope.recipientsPeople.splice(index, 1);
            $scope.recipientsPeopleIdArr.splice(index, 1);
        }
    }

HTML

<search items="orgList" list="selectedOrgs" index="$index" listitem="list.displayConfig[0].propertyValue" model="_id" on-selectupdate="updateOrgs(_id,data.selectedOrg)" ng-keyup="getOrgs(data.selectedOrg, $event)" on-delete="removeOrg($index);" />

1 个答案:

答案 0 :(得分:1)

请检查ng-repeat,您的语法似乎是倒置的,应该是list in lists而不是lists in list

<li class="tag" ng-repeat="list in lists" ng-if="lists.userName">