`
conkeyn
  • 浏览: 1506495 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

angualrjs添加动态指令(动态编译指令)

 
阅读更多

本文参考自后补全的代码:http://blog.csdn.net/liwusen/article/details/52078435

<body ng-app="myapp">
<h1>动态编译指令,动态编译指令模板内容</h1>
<div class="container" ng-controller="MyController">
    <button ng-click="addDirective()">添加动态指令</button>
    <div id="root"></div>
</div>
<!--  my-text method-from-outer="methodInCtrl()"></my-text -->
<script type="application/javascript">
    angular.module('myapp', [])
        .directive('myText', function ($compile) {
            var templatecC = '<div ng-click="hello()">Hi everyone</div>';
            return {
                restrict: 'AE',
                template: templatecC,
                scope: {
                    hello: "&methodFromOuter"
                },
                link: function (scope, ele, attr) {
                    ele.on("click", function () {
                        scope.$apply(function () {
                            //使用指令的scope进行编译模板内容,并添加到当前指令下面
                            var content = $compile(templatecC)(scope);
                            ele.append(content);
                        })
                    });
                }
            }
        })
        .controller("MyController", ["$scope", "$compile", function ($scope, $compile) {
            $scope.addDirective = function () {
                //使用controller的$scope进行编译指令,添加到指定的元素下。
                var dynamicDirective = $compile("<my-text></my-text>")($scope);
                angular.element("div#root").append(dynamicDirective);
            }
            $scope.methodInCtrl = function () {
                alert("hello 123456");
            }
        }])
</script>
</body>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics