我创建了一个新指令,该指令使用transclusion,并将scope属性设置为false (使用父作用域)。虽然它可以从周围的范围访问数据,但是指令不能更新它。
请以这里为例。当第一个文本框被修改时,所有到文本的绑定都会被更新,但是当已排除的文本框被更改时,只有相同范围中的引用才会被修改。我举个例子,我希望两个文本框都能更新对文本的所有引用。
转移是否创建了一个新的范围?这能被阻止吗?
示例中的代码:
HTML:
<script type="text/ng-template" id="tmpl.html">
<ul>
<li>I want to stay here</li>
</ul>
</script>
<div ng-controller="MyCtrl">
<h2>{{text}}</h2>
<input type="text" ng-model="text"></input>
<mydirective>
<li><input type="text" ng-model="text"></input></li>
<li>{{text}}</li>
</mydirective>
</div>联署材料:
angular.module('myApp', [])
.controller('MyCtrl',function($scope){
$scope.text = 'Somestring';
})
.directive('mydirective', function () {
return {
restrict: 'E',
transclude: true,
scope: false, //do not create a new scope
templateUrl: 'tmpl.html',
replace: false,
link : function(scope, element, attrs, ctrl, transclude){
element.find("ul").append(transclude());
}
};
});发布于 2014-08-07 12:23:33
其实我自己找到了解决办法。有一种使用transclude(scope,fn)函数的方法:
.directive('mydirective', function ($compile) {
return {
restrict: 'E',
transclude: true,
scope: false,
templateUrl: 'tmpl.html',
replace: false,
link : function(scope, element, attrs, ctrl, transclude){
transclude(scope,function(clone){
$compile(clone)(scope).appendTo(element.find("ul"));
});
}
};
});请参阅更新后的示例这里
发布于 2014-08-07 11:28:17
是transclude如何工作…的方式这是无法阻止的…
问题是字符串是基元值,所以当您在子作用域中更改它时,您将它重写为子作用域,而不是在父作用域中更新。
有一篇关于作用域的好文章:
https://github.com/angular/angular.js/wiki/Understanding-Scopes
要解决这个问题,您可以创建对象来包装文本值:
$scope.data = {text: 'Something'};http://codepen.io/anon/pen/bHpiF
解决这一问题的另一种方法是从子作用域中使用$parent:
<mydirective>
<li><input type="text" ng-model="$parent.text"></input></li>
<li>{{$parent.text}}</li>
</mydirective>http://codepen.io/anon/pen/stlcn
这取决于哪种情况更好,但总的来说,我更喜欢第一种变体,避免了范围内的原始值。
https://stackoverflow.com/questions/25180613
复制相似问题