简体   繁体   中英

Angularjs binding array element ng-repeat in directive

I'm trying to display the elements of an array using ng-repeat and a directive. The directive part is important to the solution. However the element of the array is not getting bound and displays an empty value.

The fiddle can be found at http://jsfiddle.net/qrdk9sp5/

HTML

<div ng-app="app" ng-controller="testCtrl">
    {{chat.words}}
    <test ng-repeat="word in chat.words"></test>    
</div>

JS

var app = angular.module('app', []);
app.controller("testCtrl", function($scope) {
    $scope.chat = {
        words: [
            'Anencephalous', 'Borborygm', 'Collywobbles'
        ]
    };
});
app.directive('test', function() {
    return {
        restrict: 'EA',
        scope: {
            word: '='
        },
        template: "<li>{{word}}</li>",
        replace: true,
        link: function(scope, elm, attrs) {}
    }
});

OUTPUT

["Anencephalous","Borborygm","Collywobbles"]
•
•
•   

Expected output

["Anencephalous","Borborygm","Collywobbles"]
•Anencephalous
•Borborygm
•Collywobbles   

Appreciate your help

You didn't bind word .

You have used isolate scope. If you don't bind with it's scope property,it won't work.

scope: {
    word: '='
},

Try like this

<test word="word" ng-repeat="word in chat.words"></test>

DEMO

var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
    $scope.chat= {words: [
      'Anencephalous', 'Borborygm', 'Collywobbles'
    ]};
});
app.directive('test', function() {
    return {
        restrict: 'EA',
        scope: {
            word: '='
        },
        priority: 1001,
        template: "<li>{{word}}</li>",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

Your directive needs to run before ng-repeat by using a higher priority, so when ng-repeat clones the element it is able to pick your modifications.

The section "Reasons behind the compile/link separation" from the Directives user guide have an explanation on how ng-repeat works .

The current ng-repeat priority is 1000, so anything higher than this should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM