0

I am trying to create a directive that add lots of html when user clicks a button.

angular.module('myApp').directive('testProduct', function() {
        return {
            restrict: 'A',
            link: function(scope, elem) {
                var html;
                html = '<div>… a lot of html tags and contents………….'; 
                // a lot of html tags
                //I want to link to a html file like product.html 
                //instead of defining here.
                elem.bind('click', function() {
                    $('.product').remove();
                    elem.closest('div').append(html);
                })
            }
        };
    }
);

Is there anyway I can link the html to another file? like templateUrl:product.html? I can't use it here because I only want to add those html when user clicks a button.

Thanks a lot!

1 Answer 1

1

In the click event create an element like <div ng-include="foo.html"></div> and pass it to angular.element. Then append it to the DOM. Once appended use the injected $compile service. $compile(dynamicIncludeElement)(scope).

angular.module('myApp').directive('testProduct', function($compile) {
        return {
            restrict: 'A',
            link: function(scope, elem) {
                var html = angular.element('<div ng-include="'product.html'"></div>');

                elem.bind('click', function() {
                    var compiledHtml = $compile(html)(scope);
                    elem.append(compiledHtml);
                })
            }
        };
    }
);

The other alternative would be to acquire the HTML yourself and compile it.

angular.module('myApp').directive('testProduct', function($http, $compile) {
        return {
            restrict: 'A',
            link: function(scope, elem) {

                elem.bind('click', function() {

                    $http.get('product.html')
                        .success(function(data) {
                            var compiledHtml = $compile(data)(scope);
                            elem.append(compiledHtml);
                        }
                    );

                })
            }
        };
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.