将动态加载的内容绑定到Angular

时间:2015-12-18 10:10:06

标签: javascript jquery angularjs

我想将一些由jQuery加载的动态内容绑定到Angular,但我无法让它工作。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
    <script type="text/javascript">
        var module = angular.module('ctrl', []);

        module.directive('helpMe', function() {
            return {
                restrict: 'E',
                template: '<div><button ng-click="clicker()">Click 1</button><button ng-click="create()">Create</button><div ng-hide="true">FooBar</div></div>',
                controller: ['$scope', function($scope) {
                    $scope.clicker = function () {
                        console.log('Clicked...');
                    };

                    $scope.create = function () {
                        $('#foo').contents().clone().appendTo('#bar');
                    }
                }]
            }
        });
    </script>
</head>
<body ng-app="ctrl">
    <div id="foo">
        <help-me></help-me>
    </div>
    <div id="bar">

    </div>
</body>

如果我点击&#34;点击1&#34;按钮,控制台记录它。如果我点击&#34;创建&#34;按钮,出现一组新按钮。但新的按钮不起作用。我无法找到如何完成这项工作。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

在将HTML字符串插入DOM之前,需要在HTML字符串上调用if (!places.contains(place)) print("!!! $place not in $places");,以便angular有机会执行绑定。

$compile

检查此plnkr

答案 1 :(得分:0)

试试这个会起作用: -

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
    <script type="text/javascript">
        var module = angular.module('ctrl', []);

        module.directive('helpMe', function() {
            return {
                restrict: 'E',
                template: '<div><button ng-click="clicker()">Click 1</button><button ng-click="create()">Create</button><div ng-hide="true">FooBar</div></div>',
                controller: ['$scope','$compile' function($scope,$compile) {
                    $scope.clicker = function () {
                        console.log('Clicked...');
                    };

                    $scope.create = function () {
                        $('#foo').contents().clone().appendTo('#bar');
                        $compile($('#bar'))($scope);
                    }
                }]
            }
        });
    </script>
</head>
<body ng-app="ctrl">
    <div id="foo">
        <help-me></help-me>
    </div>
    <div id="bar">

    </div>
</body>