Creating an AngularJS Directive for jQuery UI Button

最后都变了- 提交于 2019-12-03 20:15:29

You can create an isolated scope in a directive by setting the scope parameter, or let it use the parent scope by not setting it.

Since you want the ng-click from parent scope it is likely easiest for this instance to use the parent scope within directive:

One trick is to use $timeout within a directive before maniplulatig the DOM within a templated directive to give the DOM time to repaint before the manipulation, otherwise it seems that the elements don't exist in time.

I used an attribute to pass the text in, rather than worrying about transclusion compiling. In this manner the expression will already have been compiled when the template is added and the link callback provides easy access to the attributes.

<jqbutton ng-click="test(3)" text="{{title}} 3"></jqbutton>
angular.module('Components', [])
    .directive('jqbutton', function ($timeout) {
    return {
        restrict: 'E', // says that this directive is only for html elements
        replace: true,        
        template: '<button></button>', 
        link: function (scope, element, attrs) {
            // turn the button into a jQuery button
            $timeout(function () {
                /* set text from attribute of custom tag*/
                element.text(attrs.text).button();
         }, 10);/* very slight delay, even using "0" works*/
        }
    };
});

Demo: http://jsfiddle.net/gWjXc/8/

Directives are very powerful, but also have a bit of a learning curve. Also in comparison of angular to knockout, angular is more of a meta framework that in the long run has far more flexibilty than knockout

Very helpful reading for understanding scope in directives:

https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!