2016-01-27 50 views
2

我已經構建了一個指令,它有一個通過bindToController傳遞給它的對象,目的是編輯它。編輯工作很好,直到我需要取消編輯。爲了撤消,我需要創建原始對象的影子副本,進行編輯,然後根據保存或取消將其複製或丟棄。我試圖在控制器屬性中使用scope.watch在指令的鏈接屬性中實現此目的。該手錶在初始化時觸發一次,該屬性未定義,因爲沒有使用它,這是預期的。但是,一旦真正的物體被放入物業,它就不會再發生火災。在Angular Directive中撤消

我哪裏出錯了?我應該回到使用$範圍,因爲我有問題獲得控制器的參考?那隻手錶爲什麼只發射一次?

的指令:

angular.module("ISG").directive('isgEditingFundDirective', function() { 
    var ctrl = null; 
    var isgEditingFundDirectiveController = function() { 
     ctrl = this; // Getting a reference to the controller so it can be used in the link function. Is there a better way to do this? 

     this.cancel = function() { 
      // Undo the edit 
      ctrl.fund = null; 
     }; 

     this.save = function() { 
      // Save back to the original model 
      angular.copy(ctrl.shadow, ctrl.fund); 

      // Set to null because we aren't editing anymore 
      ctrl.fund = null; 
     } 
    } 

    var isgEditingFundDirectiveLink = function (scope, element, attrs) { 
     // need link so we can undo an edit 




     scope.$watch(ctrl.fund, function (orig, updated) { 
      // Trying to watch the fund property in the controller so I can create a copy for undo later. 
      // This never fires with a real value 
      angular.copy(ctrl.fund, ctrl.shadow); 
     }); 
    } 

    return { 
     restrict: "E", 
     controllerAs: 'editFundCtrl', 
     templateUrl: "/angular/editfund", 
     bindToController: { 
      fund: "=fund" 
     }, 
     controller: isgEditingFundDirectiveController, 
     link: isgEditingFundDirectiveLink 

    }; 
}); 

模板:

Editing fund 

Name: 
<input ng-model="editFundCtrl.shadow.FundName"/> 
<button ng-click="editFundCtrl.cancel()">Cancel</button> 
<button ng-click="editFundCtrl.save()">Save</button> 

<pre>{{editFundCtrl.fund}}</pre> 
+1

問題是你正試圖把觀察者上是'this'背景下,而不是範圍的變量,[這答案](http://stackoverflow.com/a/24078893/2435473)將在這種情況下幫助你 –

+0

我不明白你爲什麼需要一個手錶 – charlietfl

+0

@charlietfl消費這個指令是一種觀點列出資金。點擊一個基金會讓其控制者設置一個屬性,並傳遞給上述指令。這是從父視圖中摘錄的內容:我向其他人開放建議.... – Darthg8r

回答

1

基本上,你正在試圖把手錶放在屬於this控制器上下文的變量上。 $watch功能接受string範圍變量名稱功能,它將評估每個摘要週期。

只需將功能放入監視器中即可解決此問題。

scope.$watch(function(){ 
    return ctrl.fund; 
}, function (orig, updated) { 
    // Trying to watch the fund property in the controller so I can create a copy for undo later. 
    // This never fires with a real value 
     angular.copy(ctrl.fund, ctrl.shadow); 
}); 

否則,你也可以通過使這個angular.bind解決這個問題,請this answer

0

如果我讀這個權利,ctrl.fund是一個對象,你想

scope.$watch(ctrl.fund, function (orig, updated) { 
    // do watch stuff here 
}, true); 

true作爲第二個參數強制進行「深度觀察」,其中Angular將針對該對象執行angular.equals() e對象每次可能已經改變,這會檢查對象上的每個(非原型)屬性。

對於像String和Number這樣的原始類型,您需要將ctrl.fund作爲字符串,因爲引用將丟失更新,例如, scope.$watch('ctrl.fund', function (orig, updated)。 Angular會弄清楚如何解析它。