1

I don't know how to send my "files" variable to my custom Directive:

app.directive('chooseImages', function() {
        var files = [{name: 'a', value: 'a.jpg'}, {name: 'b', value: 'b.jpg'}, {name: 'b', value: 'b.jpg'}];
        return {
            restrict: 'A',
            template: '<ul><li ng-repeat="file in files">{{files}}</li></ul>',
        };
    })

I also tried setting "scope"

app.directive('chooseImages', function() {
        var files = [{name: 'a', value: 'a.jpg'}, {name: 'b', value: 'b.jpg'}, {name: 'b', value: 'b.jpg'}];
        return {
            restrict: 'A',
            template: '<ul><li ng-repeat="file in files">{{files}}</li></ul>',
            scope: {
                files: "@"
            },
            link: function(scope, elements, attr) {

            }
        };
    })
0

2 Answers 2

2

this will not work because "files" is not in the SCOPE.

app.directive('chooseImages', function() {
        var files = [{name: 'a', value: 'a.jpg'}, {name: 'b', value: 'b.jpg'}, {name: 'b', value: 'b.jpg'}];
        return {
            restrict: 'A',
            template: '<ul><li ng-repeat="file in files">{{files}}</li></ul>',
        };
    })

this will work:

app.directive('chooseImages', function() {
        return {
            restrict: 'A',
            template: '<ul><li ng-repeat="file in files">{{file | json}}</li></ul>',
            scope: {
                files: "="
            }
        };
    })

HTML

<div chosse-images files="outerscopefiles" ng-init="outerscopefiles=[{name: 'a', value: 'a.jpg'}, {name: 'b', value: 'b.jpg'}, {name: 'b', value: 'b.jpg'}]">
Sign up to request clarification or add additional context in comments.

2 Comments

ah...didn't know I had to declare files in the attrs
You do not need it. But you should in order to get a reusable component . The another answer, forces you to complicate things if a different image set is needed. Here ng-init is used to simplify the answer, in a practical case you should get it from "controller scope".
1

You can still have files defined inside your directive if you define your own private scope and assign the variable to it in your link function like so:

DIRECTIVE

myApp.directive('chooseImages', function() {
    return {
        restrict: 'A',
        template: '<ul><li ng-repeat="file in files">{{files}}</li></ul>',
        scope: true,
        link: function(scope, elements, attr) {
            scope.files = [{name: 'a', value: 'a.jpg'}, {name: 'b', value: 'b.jpg'}, {name: 'b', value: 'b.jpg'}];

        }
    };
})

HTML

<div choose-images ></div>

Plunkr here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.