I am relatively new to angularjs, and what I wanna do is to create a ngView-like component.
so there is a very important process is to inject a controller to DOM.
suppose we have a DOM,
<div>
<span>Name: {{name}}</span>
</div>
and a controller,
function InjectedController($scope) {
$scope.name = "Leo Yuan";
}
What I wanna do is to inject controller "InjectedController" into division,
I tried to write code like ngView does,
$("div").contents().data('$ngControllerController', InjectedController);
but it still didn't work, something wrong?
You can do this by including the controller directly into the HTML. Make sure to have this HTML stored as a template or a variable and then load it as a string.
<div data-ng-controller="%%controller%%">
<span>Name: {{name}}</span>
</div>
The replace the %%controller%% part with whatever controller you want using JavaScript.
Then either have that run directly or compile that HTML by itself
var templateHTML = "..."; //either download it with XHR or make it an inline template
templateHTML = templateHTML.replace('%%controller%%', injectedController);
//inject the $compile service into the function body
//grab the scope if it's not already there
$scope = $scope || angular.element(document).scope();
//this should run the controller automatically
$compile(templateHTML)($scope);