2015-10-22 38 views
1

我有下面的指令,它設置了一個綁定到我觀察的控制器$ scope屬性的屬性。問題是觀察者從來沒有觸發過,我正在遊走爲什麼。

更新!

解決方案

更多的挖掘後,我發現這個很酷的文章由吉姆·霍斯金斯約$範圍。$適用(),它解決了我的問題。

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

mod.directive('gsGridSorting', function($modal, $timeout) { 
    return { 
     restrict: 'A', 
     link: function($scope, $element, $attrs) { 
      var lastSortedCol; 
      $element.on('click', 'th.sorting', function (event) { 
       var target = $(event.target); 
       //The missing piece! 
       $scope.$apply(function() { 
        $scope.sortColumn = target.data('column'); 
       }) 
      }); 
     }, 
     scope: { 
      sortColumn: '=' 
     } 
    }; 
}); 

<thead gs-grid-sorting sort-column="sortColumn"> ... </thead> 

看着沒有成功我的$ scope屬性。

$scope.$watch('sortColumn', function (oldValue, newValue) { 

}); 
+0

看起來你看屬性。這可能有所幫助:http://stackoverflow.com/questions/15911300/is-it-possible-to-watch-attributes-changes – lintmouse

+0

我很困惑,你想看'sortColumn'或'sortDir'嗎?導致你的2個代碼片段不同 – user2718281

+0

是的,但我正在從我的控制器看它,另一個帖子是當你想從指令看它。 – bozhidarc

回答

0

我認爲你可以使用$watch與功能相同的後續代碼:

mod.directive('gsGridSorting', function($modal, $timeout) { 
    return { 
     restrict: 'A', 
     link: function($scope, $element, $attrs) { 
      var lastSortedCol; 

      $element.on('click', 'th.sorting', function (event) { 
       var target = $(event.target); 
       $attrs.sortColumn = target.data('column'); 
      }); 
      $scope.$watch (function(){ 
       return $attrs.sortColumn; 
      },function(oldValue,newValue){ 
       console.log(newValue); 
      }); 
     }, 
     scope: { 
      sortColumn: '=' 
     } 
    }; 
}); 
相關問題