Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one directive inside another directive template in Angularjs

I am pretty new to Angularjs and try to implement one directive inside another directive . I have a child directive basetext which handle basic input events and myTextbox which handle other task related to input. I have made a simple plunker to demonstrate my problem. I have implemented as

In html

<div my-textbox placeholder="'Input the value'" caption="Name:"></div>

In myTextbox directive template function :

template: function (elem, attrs) {
        return ("<label>" + attrs.caption + "</label>\
                 <input class='inputText' basetext='' " + "placeholder=" + attrs.placeholder +"/>");
},

and my basetext directive :

app.directive("basetext", function () {
    return {
        restrict:'A',
        scope:{}
        template: "<input ng-focus='isFocus()' ng-blur='isBlur()'/>",
        link: function (scope, element, attrs) {

            scope.isBlur = function () {
                alert("is blurred");
            }
            scope.isFocus = function () {
                alert("is focused");
            }
        }
    }
});

The problem is that the blur event and focus event of basetext directive isn't working at all . Any suggestion to solve this problem ? Thanks

like image 712
Rebel Avatar asked Nov 19 '25 18:11

Rebel


1 Answers

Inspect the element, and you will see

enter image description here

template of basetext is inside the input tag which is invalid.

You need to put replace: true, property on basetext directive as then it will replace the element which the child directive template.

app.directive("basetext", function () {
    return {
        restrict:'A',
        replace: true,
        scope:{},
        template: "<input ng-focus='isFocus()' ng-blur='isBlur()'/>",
        link: function (scope, element, attrs) {

            scope.isBlur = function () {
                alert("is blurred");
            }
            scope.isFocus = function () {
                alert("is focused");
            }
        }
    }
});

here is the DEMO

like image 164
Kalhan.Toress Avatar answered Nov 22 '25 09:11

Kalhan.Toress



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!