AngularJS:动态编译指令模板时正确的范围绑定 鉴于 适用于元件E的指令D1 向指令D1传递包含指令D2的模板 指令D2已订阅ngModel更新 指令D1使用指令D2编译模板 指令D1和D2被视为相互独立 指令D1和D2具有独立的作用域 (指令D1可能与DOM分离,但保留在内存中) 客观的 使指令D2对应用D1的元素E的范围变化作出反应
index.htmlAngularJS:动态编译指令模板时正确的范围绑定 鉴于 适用于元件E的指令D1 向指令D1传递包含指令D2的模板 指令D2已订阅ngModel更新 指令D1使用指令D2编译模板 指令D1和D2被视为相互独立 指令D1和D2具有独立的作用域 (指令D1可能与DOM分离,但保留在内存中) 客观的 使指令D2对应用D1的元素E的范围变化作出反应,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,index.html <div ng-app="myApp" ng-controller="MainCtrl"> <label> <u>model: </u> <input type="text" ng-model="someValue" outer="tmpl.html"/> <hr/> </label> <script type="text/ng-template" id="t
<div ng-app="myApp" ng-controller="MainCtrl">
<label>
<u>model: </u>
<input type="text" ng-model="someValue" outer="tmpl.html"/>
<hr/>
</label>
<script type="text/ng-template" id="tmpl.html">
<inner test="123"></inner>
</script>
<script src="angular.js"></script>
型号:
app.js
(function (ng) {
var app = ng.module('myApp', []);
app.controller('MainCtrl', [
'$scope',
function ($scope) {
$scope.someValue = 'Hello, World!';
}
])
// directive D2
.directive('inner', function () {
return {
restrict: 'AE',
replace: true,
template: '<p>{{model || "N/A"}}</p>',
scope: { model: '=ngModel' },
link: function (scope, element, attrs) {
scope.$watch('model', function (newValue, oldValue) {
if (!ng.isDefined(oldValue) && !ng.isDefined(newValue)) {
return;
}
// do stuff...
});
}
};
})
// directive D1
.directive('outer', [
'$templateCache',
'$compile',
function ($templateCache, $compile) {
return {
restrict: 'AE',
scope: {},
link: function (scope, element, attrs) {
var template = $templateCache.get(attrs.outer);
var compiled = $compile(template)(scope);
element.parent().append(compiled);
}
};
}
]);
})(angular);
(功能(ng){
var app=ng.module('myApp',[]);
应用程序控制器('MainCtrl'[
“$scope”,
职能($范围){
$scope.someValue='Hello,World!';
}
])
//指令D2
.指令('内部',函数(){
返回{
限制:“AE”,
替换:正确,
模板:“{{model | |“N/A”}”,
作用域:{model:'=ngModel'},
链接:函数(范围、元素、属性){
范围:$watch('model',函数(newValue,oldValue){
如果(!ng.isDefined(oldValue)和&!ng.isDefined(newValue)){
返回;
}
//做些事情。。。
});
}
};
})
//指令D1
.指令(“外部”[
“$templateCache”,
“$compile”,
函数($templateCache,$compile){
返回{
限制:“AE”,
作用域:{},
链接:函数(范围、元素、属性){
var template=$templateCache.get(attrs.outer);
var compiled=$compile(模板)(范围);
element.parent().append(已编译);
}
};
}
]);
})(角度);
不停摆弄
这里有一个过于简化的版本:
例子
D1是一个popover小部件,可以配置为插入HTML作为其内容。
D2是一个二维码小部件,用于查看模型并在更改时进行更新
问题
ngModel绑定没有正确完成,我没有从中获得更新。我在这里做错了什么?
范围:{model:'=ngModel'},
这将属性model
绑定到内部
元素的属性ng model
中定义的属性,因为您使用的是元素形式的指令。您的内部
元素没有这样的属性
但即使有,第二个问题是内部
的父范围是外部
的范围,这也是一个孤立的范围someValue
是在控制器的作用域中定义的,因此Internal
没有机会直接与someValue
建立绑定,无论您选择的绑定类型如何
解决方案取决于您的具体需求。请参阅以获得一个可能的解决方案。@JohnDoe D2依赖于E(事实上,它的ng模型
),而这两者之间的唯一链接是D1。因此,您可以使用另一个D1,即了解D2的D1,或另一个了解模型的D2(即模板)。