2014-09-22 54 views
0

HTML:在 '點擊' 回調函數傳遞範圍angularjs

<body ng-app="EditApp"> 
    <div ng-controller="MainController"> 
    <h1 click-to-edit>This is something I want to edit</h1> 

    </div> 
    </body> 

的Javascript:

angular.module("EditApp", []) 
.controller("MainController", ['$scope', function($scope){ 
    $scope.text = "This is something I would like to edit"; 

}]) 
.directive("clickToEdit", function(){ 
    return { 
    restrict: 'EA', 
    template: " <input type='text' value='{{ text }}' ng-show='showInput'/> <div ng-transclude ng-hide='showInput'></div>", 
    transclude: true, 
    link: function (scope, element, attrs) { 
     scope.showInput = false 
     element.on("click", function(){ 

     scope.$parent.showInput = true 

     }) 
    } 
    } 
}) 

爲什麼showInput不改變?或者是,但我必須做一個scope.$apply()?我是否應該在點擊功能中以某種方式傳遞scope

謝謝!

回答

1

將附加的ng-click放在包容容器上,也不需要在範圍上使用$parent。是的,它不更新,因爲

  • 你正在更新錯誤的範圍。
  • 角不知道的範圍,除非你做外部註冊的處理程序進行更新,或者等到明年消化週期刷新不會發生: -

    element.on("click", function(){ scope.showInput = true scope.$apply(); });

嘗試: -

.directive("clickToEdit", function(){ 
    return { 
    restrict: 'EA', 
    template: " <input type='text' value='{{ text }}' ng-show='showInput'/> <div ng-click='showClick()' ng-transclude ng-hide='showInput'></div>", 
    transclude: true, 
    link: function (scope, element, attrs) { 
     scope.showInput = false; 
     scope.showClick = function(){ 
     scope.showInput = true 
     } 
    } 
    } 
}); 

Plnkr

Plnkr2 update text on blur

+0

是的!這是完美的 - 不能相信我沒有想到ngclicks – 2014-09-22 20:22:32

+0

@MohamedElMahallawy儘可能多我會建議採用角度註冊事件的方式,所以你最終不會遇到這樣的範圍同步問題。:) – PSL 2014-09-22 20:24:56