在DOM元素上创建角度范围 [英] Create angular scope on DOM element
问题描述
我需要创建一个新的角度范围并将其附加到DOM元素。我正在修改第三方控件,所以我没有选择只使用一个指令。
I need to create a new angular scope and attach it to a DOM element. I'm modifying a third party control so I don't have the option of just using a directive.
我需要执行以下操作:
... = thirdPartyCallbackfunction(domElement){
var myNewScope = $scope.$new(true);
myNewScope.title = 'Hello';
domElement.scope = myNewScope; //???
}
此外,我尝试添加 ng-scope
手动添加到DOM元素,但是ng-inspector会向我显示它不会创建一个新的子范围。
Also, I've tried adding ng-scope
manually to the DOM element, but ng-inspector shows me that it's not creating a new child scope.
$(domElement).scope();
在尝试时给我根本的范围。
Gives me the root scope when trying that.
文档也不是非常有用。
推荐答案
你应该使用$ compile服务。
You should use $compile 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>
控制器:
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
用于评估HTML片段或DOM元素(包裹在jqLite对象中)。例如,代替DOM元素,你可以使用一些内联绑定的HTML模板:
var content =< ul>< li ng-repeat ='city in cities' > {{城市}}< /立GT;< / UL>中
var list = angular.element(content); //从上面的模板创建jqLite对象;
下一步是使用 $ compile
服务对象,这是一个函数这返回另一个函数,然后将其用于生成内容。
var compileFn = $ compile(list);
$compile
is used to evaluate HTML fragment or DOM element (wrapped in jqLite object). For example, instead of the DOM element, you could have used some html template with inline 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;
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);
一旦你有编译功能,你调用它将范围对象作为即将到来的评估的上下文传递,基本上将元素与范围相关联。
compileFn(scope);
现在,模板中包含的绑定/表达式将使用您传递的范围进行评估,并更新jqLite对象( list
),但是没有返回值,所以在这种情况下,你必须手动添加更新的列表
对象到DOM希望这样澄清了一下服务。
Once you have the compilation function, you invoke it passing the scope object as the context for the upcoming evaluation, basically linking the element with the scope.
compileFn(scope);
Now bindings/expressions contained within the template will be evaluated using the scope you passed it and update the jqLite object (list
), but there will be no return value, so in this case you would have to manually add the updated list
object to DOM. Hope this clarifies the service a bit.
这篇关于在DOM元素上创建角度范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!