Gabriel
Gabriel

Reputation: 439

How to correctly pass an object to a custom directive?

I have a very "simple" goal: I have a kind of form creator, and this directive is expected to "render" the content of the form.

For that, I created a custom directive which I am planing to pass the object and create a logic for rendering trough templates. However, I am failing to pass the object to the custom directive

HTML:

<div ng-controller="myController">

    <p>Components starts</p>
    <div ng-repeat="item in items">
        <!-- <p>{{item}}</p> -->
        <my-component obj="item" ></my-component>
    </div>
    <p>Components ends</p>

</div>

JS

angular.module('myApp', [])
.controller('myController', function($scope) {

    $scope.items = [
        { type: 'TextArea', data: 'Somedata1', mandatory: true },
        { type: 'List', data: 'Somedata2', mandatory: false },
        { type: 'Select', data: 'Somedata3', mandatory: true }];

})
.directive('myComponent', function() {
    return {  
        restric: 'E',
        scope: { obj: '=obj' },
        template: '<div> This is the template for {{obj.type}} </div>'
    };
});

I have made and changed the code many times with different examples I got on the web, but after 2 days I was not able to make it work (yes, it is shameful)

Here is the fiddle link

I know the issue is when passing to the directive, because if I remove the comment tag from the ng-repeat, the data is show correctly, but if I try to use the directive it does not work.

Please, can anyone help me and explain me why this is not working and what am I missing?

Upvotes: 1

Views: 44

Answers (1)

sfletche
sfletche

Reputation: 49714

Thanks for providing the jsfiddle. I'm not sure I would have spotted the problem without it.

Turns out you were misspelling restrict (you left off the 't' at the end), and you needed to leave out the reference to scope in the view.

Check out your updated (and working) fiddle here.

Upvotes: 1

Related Questions