簡體   English   中英

AngularJS:嵌入創建新范圍

[英]AngularJS: Transclusion creates new scope

我創建了一個使用轉儲的新指令,並將scope屬性設置為false (使用父級作用域)。 盡管它可以從周圍的范圍訪問數據,但該指令無法更新它。

請在這里的例子。 修改第一個文本框時,所有與文本的綁定都將更新,但是當更改后的文本框時,僅修改同一作用域中的引用。 在我的示例中,我希望兩個文本框都更新對text的所有引用。

包含是否會創建新的范圍? 可以防止這種情況嗎?

示例中的代碼:

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>

JS:

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());
        }
    };
});

是超越工作的方式……這是無法避免的……

問題在於字符串是原始值,因此在子作用域中更改字符串時,您將其覆蓋子作用域,但未在父作用域中更新。

有一篇關於范圍的好文章:

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

這取決於情況,哪個更好,但總的來說-我更喜歡第一個變體,避免在范圍內使用原始值。

我實際上自己找到了解決方案。 有一種方法可以使用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"));
            });
        }
    };
});

這里查看更新的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM