angularjs pass newly created array in attribute to directive

后端 未结 3 1968
余生分开走
余生分开走 2020-12-31 10:17

I\'ve created this fiddle to show my issue...

http://jsfiddle.net/dQDtw/

I\'m passing a newly created array to a directive, and everything is working out jus

相关标签:
3条回答
  • 2020-12-31 10:53

    That error is because your directive is not able to interpret the array as an array, Try this:

    <body ng-app="myApp" ng-controller="ctrl1">
        <test-dir fam-people='people'> </test-dir>
    
    </body>
    
    
    
    var myApp = angular.module('myApp', []);
    
    myApp.directive('testDir', function() {
                    return { restrict: 'E'
                           , scope: { famPeople: '=' }
                           , template: "<ol> <li ng-repeat='p in famPeople'> {{p}}"
                           };
            });
    

    Controller and directive:

    myApp.controller("ctrl1",function($scope){
    $scope.people=[1,4,6];
    });
    

    EDIT

    or you could pass it in as an attribute and parse it to an array:

    <body ng-app="myApp" >
        <test-dir fam-people='[1,4,6]'> </test-dir>
    
    </body>
    

    Directive:

    var myApp = angular.module('myApp', []);
    
    myApp.directive('testDir', function() {
                    return { restrict: 'E', 
                            //scope: { famPeople: '=' },
                           template: "<ol> <li ng-repeat='p in people track by $index'> {{p}}",
                            link:function(scope, element, attrs){
                          scope.people=JSON.parse(attrs.famPeople);
                            }
                           };
            });
    

    See fiddle.

    0 讨论(0)
  • 2020-12-31 11:02

    JSON parse doesn't work as effective when the array contains string.

    For example:

    <file-handler fh-services="['BOX','DROPBOX']"></file-handler>
    

    In the directive you can use scope.$eval to convert what appears in the attribute to an array.

    scope.$eval(attrs.fhServices)
    
    0 讨论(0)
  • 2020-12-31 11:05

    what about:

    <body ng-app="myApp">
        <test-dir fam-people='1;4;6'> </test-dir>
        <test-dir fam-people='2;1;0'> </test-dir>
    </body>
    

    and

        var myApp = angular.module('myApp', []);
    
        myApp.directive('testDir', function() {
                    return { restrict: 'E', 
                            //scope: { famPeople: '=' },
                           template: "<ol> <li ng-repeat='p in people track by $index'> {{p}}",
                            link:function(scope, element, attrs){
                          scope.people= attrs.famPeople.split(';');
                            }
                           };
            });
    

    cleanest solution?

    0 讨论(0)
提交回复
热议问题