我正在将 $http-retrived, $compile-d 模块 HTML 添加到元素中。链接和编译方法没有触发。我究竟做错了什么?
我尝试了许多不同的方法将模块放入页面,使用和不使用 ng-repeat,我已经能够渲染模块的视图,并且初始指令工厂函数会触发,但是链接和编译那些没有。
HTML:
<body>
<div class="container {{device}}" ng-cloak>
<div modules></div>
</div>
</body>
JavaScript:
var ROOT_URL = "/";
angular.module("app")
.directive("modules", ["$q", "$http", "$templateCache", "$compile", function ($q, $http, $templateCache, $compile) {
"use strict";
return {
restrict: "A",
replace: true,
template: "<div id=\"module-list\"></div>",
link: function($scope, $element, $attrs) {
var moduleHtml = "";
var getModuleHtml = function(moduleData) {
var moduleName = moduleData.directive;
var moduleUrlBase = ROOT_URL + "views/directives/";
var defer = $q.defer();
var moduleUrl;
// convert hyphens to camel-case
moduleName = moduleName.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
moduleUrl = moduleUrlBase + moduleName + ".html";
$http.get(moduleUrl)
.success(function(moduleHtml) {
defer.resolve(moduleHtml);
});
return defer.promise;
};
var addModuleToPage = function(moduleData) {
//$scope.$apply($element.append("<div module " + $scope.modules[i].directive + " ></div>"));
getModuleHtml(moduleData).then(function(moduleHtml) {
moduleHtml = angular.element(moduleHtml);
$element.append($compile(moduleHtml)($scope.$new(true)));
});
};
$scope.$watch("modules", function() {
if ($scope.modules && $scope.modules.length) {
for (var i = 0, modulesLen = $scope.modules.length; i < modulesLen; i++) {
if (typeof $scope.modules[i].directive !== "undefined") {
addModuleToPage($scope.modules[i]);
}
}
}
});
}
};
}])
.directive("module", [function () {
"use strict";
return {
restrict: "A",
replace: false,
scope: {}
};
}])
.directive("hero", [function () {
"use strict";
console.log("factory");
return {
templateUrl: ROOT_URL + "views/directives/eventP1.html",
restrict : "A",
replace : true,
transclude : false,
require : "module",
compile: function() {
console.log("compile");
}
};
}]
);
使用 AngularJS 1.0.5。