<!doctype html> <html ng-app="app"> <head> <title></title> <meta charset="utf-8" /> <script src="https://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="http://cdn.bootcss.com/angular.js/1.4.0/angular.min.js"></script> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"> <style> *{ margin: 0;padding:0; } </style> </head> <body> <div id="myform" ng-controller="myform"> <div app-page data-x="{{x}}" data-y="{{y}}"> <div class="box">box</div> </div> </div> <script type="text/javascript"> var app = angular.module("app", function () {}); app.controller("myform",function($scope,$compile,$timeout) { $scope.x = 100; $scope.y = 100; $timeout(function(){ $("#myform").html('') var html = '<div app-page data-x="130" data-y="130" style="position: absolute;top:130px;left:130px;"><div class="box">box</div></div>'; $("#myform").append($compile(html)($scope)); },3000); }); app.directive("appPage", function () { return { restrict: "A", replace: true, template: '<div data-x="{{x}}" data-y="{{y}}" style="position: absolute;top:{{y}}px;left:{{x}}px;"><div class="box">box</div></div>', link: function (scope, element, attrs) { console.log("11"); scope.x = attrs.x; scope.y = attrs.y; } } }); /** * 经过3秒以后重新替换html,为什么style样式 ,data-x ,data-y 都复制了3份啊..这是什么原因啊? */ </script> </body> </html>
经过3秒以后重新替换html,为什么style样式 ,data-x ,data-y 都复制了3份啊..是因为重复调用了多次指令的原因吗?怎么解决这个问题?