Search code examples
javascriptangularjsangularjs-directivetransclusion

AngularJS : directive ng-transclude to input value


Im trying create a directive which add ng-transclude value to input field value attribute in html template:

directive I've created:

module.directive('editInput', function(){
    return {
        restrict: 'E',
        scope: {
            value: '='
        },
        transclude: true,
        template: '<p ng-show="value == false" ng-transclude></p>' +
        '<input ng-show="value == true" placeholder="" value="" ng-transclude/>'
    }
});

looking for something which adds ng-transclude value to value attribute in input element

template:

<edit-input value="isEditModeActive">{{person.name}}</edit-input>

currently I get this html output:

<input ng-show="value == true" placeholder="" value="" ng-transclude="" class="">
<span class="ng-binding">Name</span></input>

but really I need this html output:

<input ng-show="value == true" placeholder="" value="Name">

Solution

  • script.js:

    angular.module('app', [])
    .controller('ctrl', function($scope) {
      $scope.person = {};
      $scope.person.name = 'Rahul';
    })
    .directive('editInput', function(){
        return {
            restrict: 'E',
            scope: {
                value: '=',
                editName: '@'
            },
            transclude: true,
            template: 
            '<p ng-show="value == false" ng-transclude></p>' +
            '<input ng-show="value == true" placeholder="" value="{{editName}}" />'
        }
    });
    

    index.html:

    <!doctype html>
    <html lang="en" ng-app="app">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body ng-controller="ctrl">
        <script src= "angular.js"></script>
    
        <script src= "script.js"></script>
    
        <edit-input value="true" edit-name="{{person.name}}">{{person.name}}</edit-input>
        {{person.name}}
    </body>
    </html>