Reputation: 61061
Let me first post the explanation of what I am trying to accomplish with broken-pseudocode:
// controllers.js
angular.module('myApp.controllers', []).
controller('MyCtrl1', [function() {
var template = '<div my-directive></div>';
var div = $("#view1").append(template);
var code = http.get('/dynamic-code-for-directive');
angular.module('myApp.directives').directive(eval(code));
}])
// Index.html
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<ul class="menu">
<li><a id="view1" href="#/view1">view1</a></li>
</ul>
</body>
</html>
// code.js returned by "GET /dynamic-code-for-directive"
function(scope, element){ $("#view1").append("Hello World");
Basically I want the server to provide the definition for the directive, and then generate one on the fly.
The problem, it seems, is with the append
call above --- it does not recognize the template as the directive, so the directive code never gets called.
Has anyone ever tried to accomplish anything similar to this?
Upvotes: 1
Views: 120
Reputation: 6269
There is some things you are doing wrong, you are doing DOM manipulation inside a controller, which is wrong and not an appropriate use of angularjs.
To use $compile you need to be inside a directive. It would look something like:
app.directive('directiveCreator', function($compile, $http) {
return function(scope, element, attrs) {
var template = '<div my-directive></div>';
element.html(template);
var code = $http.get('/dynamic-code-for-directive');
app.directive('myDirective', function() {
var link = eval(code);
return {
link : link
}
}
$compile(element.contents())(scope);
}
);
};
There might be mistakes but it would be something like that.
Upvotes: 0
Reputation: 3493
try doing it in the following order
var code = http.get('/dynamic-code-for-directive');
angular.module('myApp.directives').directive(eval(code)); //ie adding the directive definition
then make a template but one step that you are missing is COMPILING it
$scope.template = $compile(<div my-directive></div>')($scope);
then append it!
angular.element("#view1").append($scope.template);
please revert back with the results
Upvotes: 1