On the docs I saw an example of compiling "something" added later.
var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
$(document.body).append($div);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element($div).scope();
$compile($div)(scope);
});
I've added this code on a jquery ready function, but I have two problems:
First is an error:
Argument 'MyCtrl' is not a function, got undefined
.
The second is that I don't know how to make that content.label
works! I've added it to the scope
but it doesn't work. How should I call my controller to see working the data binding of content.label
?
MY FINAL MODIFIED CODE IS:
var app = angular.module('app',[]);
$(function(){
app.controller('MyCtrl',function($scope){
$scope.content = 123;
});
var $div = $('<div ng-controller="MyCtrl">{{content}}</div>');
$(document.body).append($div);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element($div).scope();
$compile($div)(scope);
});
});
Compiler is an AngularJS service which traverses the DOM looking for attributes. The compilation process happens in two phases. Compile: traverse the DOM and collect all of the directives. The result is a linking function.
In AngularJS, Interpolation is a way to transfer the data from a TypeScript code to an HTML template (view), i.e. it is a method by which we can put an expression in between some text and get the value of that expression.
Solution bindToController : Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.
AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.
UPDATE
You should start a digest cycle after compiling new markup, in order to build all bindings and fire watchers. This can be done by calling scope.$digest();
:
$compile($div)(scope);
scope.$digest();
The result should look like:
var app = angular.module('app',[]);
app.controller('MyCtrl',function($scope){
$scope.content = 123;
});
angular.element(document).ready(function () {
var $div = $('<div ng-controller="MyCtrl">{{content}} </div>');
$(document.body).append($div);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element($div).scope();
$compile($div)(scope);
scope.$digest();
});
});
http://plnkr.co/edit/dDNBxf8SowKTPgnVj0tF?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With