我已經構建了一個指令,它有一個通過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>
問題是你正試圖把觀察者上是'this'背景下,而不是範圍的變量,[這答案](http://stackoverflow.com/a/24078893/2435473)將在這種情況下幫助你 –
我不明白你爲什麼需要一個手錶 – charlietfl
@charlietfl消費這個指令是一種觀點列出資金。點擊一個基金會讓其控制者設置一個屬性,並傳遞給上述指令。這是從父視圖中摘錄的內容: isg-editing-fund-directive>我向其他人開放建議.... –
Darthg8r