简体   繁体   中英

Use $compile inside Angular link function AND access directive arguements

I am making a directive in angular.js 1.x

I call the directive as follows:

<mydirective dirarg={{value-1}}></mydirective>

I would like to create the directive by putting code to manipulate the DOM in the directive's link function. The structure of the DOM generated by the link function is dependant on the value of dirarg, and I would like some elements to have a ng-click attribute.

I have managed to get ng-clicks to work by doing the following:

app.directive('calendar',function($compile){
    return{
        link: function(scope, element, attributes){
            element.append($compile("<button ng-click='testt()'>hi</button>")(scope));
        } 
    }
});

When I click the button generated by this directive, the function testt() runs. However, the call to testt() breaks if I try to access dirarg .

app.directive('calendar',function($compile){
    return{
        scope:{
            dirarg: '@'
        },
        link: function(scope, element, attributes){
            element.append($compile("<button ng-click='testt()'>"+scope.dirarg+"</button>")(scope));
        } 
    }
});

This code now populates the text of the button with dirarg, but the ng-click functionality breaks. Does somebody know how I can both have ng-click working, and access the arguments to the directive?

To be clear, this button is just an example. My actual situation is a lot more complicated than a button, so don't tell me better ways to make buttons in angular.

When add scope property to directive option it makes isolated scope for directive, you need pass testt function inside directive too, or define testt function inside directive link functiontion

<mydirective dirarg={{value-1}} testt="testt"></mydirective>

app.directive('calendar',function($compile){
    return{
        scope:{
            dirarg: '@',
            testt: '='

        },
        link: function(scope, element, attributes){
            element.append($compile("<button ng-click='testt()'>"+scope.dirarg+"</button>")(scope));
        } 
    }
});

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