Create an angular scope for the DOM element

I need to create a new angular region and attach it to the DOM element. I am modifying a third-party control, so I can’t just use the directive.

I need to do something like:

... = thirdPartyCallbackfunction(domElement){ var myNewScope = $scope.$new(true); myNewScope.title = 'Hello'; domElement.scope = myNewScope; //??? } 

Also, I tried to add ng-scope manually to the DOM element, but the ng-inspector shows me that it does not create a new content area.

 $(domElement).scope(); 

Gives me the root area when trying this.

docs also didn't help much.

+5
source share
1 answer

You must use the compilation service.

HTML:

 <div ng-app="myApp" ng-controller="myCtrl"> <p> Top scope: {{number}}</p> <p> Top scope: {{myProp}}</p> <!-- Undefined in the top-level scope --> <div id = "child"> <p> New scope: {{myProp}}</p> </div> </div> 

Controller:

 angular.module("myApp", []).controller("myCtrl", ["$scope", "$compile", function($scope, $compile){ $scope.number = 35; var myFunc = function(){ var innerElem = angular.element(document.querySelector("#child")); var innerScope = $scope.$new(); innerScope.myProp = 55; var compileFn = $compile(innerElem); compileFn(innerScope); } myFunc(); }]); 

$compile used to evaluate an HTML fragment or a DOM element (wrapped in a jqLite object). For example, instead of a DOM element, you could use some html template with built-in bindings: var content = "<ul><li ng-repeat='city in cities'>{{city}}</li></ul>" var list = angular.element(content); //create jqLite object from the template above; var content = "<ul><li ng-repeat='city in cities'>{{city}}</li></ul>" var list = angular.element(content); //create jqLite object from the template above; The next step is to use the $compile service object, which is a function that returns another function, which will then be used to generate the content. var compileFn = $compile(list);

Once you have the compilation function, you call it by passing the scope object as the context for the upcoming evaluation, basically associating the element with the scope. compileFn(scope); Now the bindings / expressions contained in the template will be evaluated using the scope you passed in and update the jqLite ( list ) object, but there will be no return value, so in this case you will have to manually add the updated list object for the DOM. Hope this clarifies the service a bit.

+4
source

Source: https://habr.com/ru/post/1232784/


All Articles