1

I'm new to angular, and I'm trying to solve this problem. I have the following html

<div ng-repeat="el in elements">
    <div ng-basicmenuinput basic-input="el"></div>
</div>

and in controller I have the following elements

        $scope.elements = [
            {
                type: "A",
                name: "AAA"
            },
            {
                type: "B",
                name: "BBB"
            }

        ];

and I've created the following directive

.directive('ngBasicmenuinput', function () {
    return {
        restrict: 'A',
        replace: true,
        scope: {
            basicInput: "="
        },
        template: function () {
            return '<div class="basicMenuInput">{{basicInput.name}}</div>';
        }
    }
})

now on template function I want to do something like this:

    template: function () {
        if(basicInput.type=="A") // basicInput is undefined
        return '<div class="basicMenuInput">{{basicInput.name}}</div>';
    }

but basicInput is undefined. Basically all I want to do is return a different template based on basicInput.type. Is it okay( in an angular way ) what I did?

3 Answers 3

2

please note. to use your own custom directive inside of your view(html) you need to take note of the naming convention. if you name ur directive ngBasicMenuInput, then its going to get normalised into " ng-basic-menu-input " taking into consideration the camelCase.

Sign up to request clarification or add additional context in comments.

Comments

1

Use ng-if / ng-switch / ng-show / ng-hide

You can't place a condition like that in the template. instead, assist angular with this view decision in your template like this:

Example using ng-if :

<div ng-if="basicInput.type=='A'" class="basicMenuInput">
   {{basicInput.name}}
</div>
<div ng-if="basicInput.type=='B'">
   ...
</div>

Comments

1
template: function () {
        return '<div ng-if=basicInput.type=="A" class="basicMenuInput">{{basicInput.name}}</div>';
    }

2 Comments

Could you add a description as to how this answers the question?
@LawrenceAiello ng-if would add the dom to the document only if condition basicInput.type=="A" evaluates to true, and thats what OP wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.