2015-07-22 16 views
0

我有兩個指令。 當我更改父範圍中的數據從子範圍,數據沒有變化。 您可以通過單擊李元素之一進行測試。爲什麼父母範圍直接不變

http://plnkr.co/edit/7ewMokT2vTnLWBFEdm14?p=preview

HTML

<ez-select> 
<ez-option title="option 1"> 
     Option 1 inside 
     <input ng-model="x">{{x}} 
    </ez-option> 
    <ez-option title="option 2"> 
     Option 2 inside 
    </ez-option> 
</ez-select> 

JAVASCRIPT

m.directive('ezSelect',function(){ 
    return { 
     template:'<ul ng-transclude></ul><br>Selected: {{selected}}', 
     transclude:true, 
     link:function($scope){ 
     $scope.selected=1 
     } 
    } 
    }); 
    m.directive('ezOption',function(){ 
     return { 
      template:'<li></li><div ng-show=selected ng-transclude class=body></div>', 
      link:function ($scope,iElement,iAttrs,controller,tanscludeFn){ 
       iElement.find('li').html(iAttrs.title) 
       iElement.closest('ez-select').find('.body') 
       iElement.find('li').on('click',function(){ 
        $scope.selected=false 
        $scope.$parent.selected=2 
       }) 
      }, 
      controller:function($scope){ 
       $scope.selected=false 
      }, 
      transclude:true 
     } 
    }) 
+1

注意:總是在'ng-model'中有一個點(或'[]')。你正在使用基元,他們沒有像對象一樣的繼承,所以你將在子範圍中失去2路綁定。否則,這與您最後一個問題是一樣的問題 – charlietfl

回答

1

檢查這方面的工作演示:http://plnkr.co/edit/lRKhAHB9zmHKKrcdD6nO?p=preview

需要兩個修改。

首先,由於charlietfl評論,總是使用一個對象來共享模型。有關詳細說明,請查看此優秀文章:Understanding Scopes。在你的例子中,我將selected更改爲data.selected

其次,由於onClick事件是出角的生命週期中,你需要使用$scope.$apply手動觸發$digest週期。所以:

$scope.$apply(function() { 
    $scope.selected=false; 
    $scope.$parent.data.selected=2; 
}); 

關於您的編碼風格的一些問題:

  • 在會議中,我們使用scope代替$scope在鏈接功能
  • 相反的element.on,使用ng-click
相關問題