简体   繁体   中英

AngularJS directive with custom template

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?

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.

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

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>

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