![](/img/trans.png)
[英]How to access form object with two-way-binding in angular directive without isolated scope
[英]angular.js directive two-way-binding scope updating
我想使用指令在前端具有一些點擊編輯功能。 這是我為此使用的指令: http : //icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/
'use strict';
angular.module('jayMapApp')
.directive('clickToEdit', function () {
return {
templateUrl: 'directives/clickToEdit/clickToEdit.html',
restrict: 'A',
replace: true,
scope: {
value: '=clickToEdit',
method: '&onSave'
},
controller: function($scope, $attrs) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
$scope.method();
};
}
};
});
我在指令中添加了第二個屬性,以在用戶更改值后更新數據庫等之后調用方法。方法(此處為“ $ onSave”)稱為“罰款”,但似乎父范圍尚未更新。我在指令末尾調用該方法。 有沒有一種方法可以調用,但是可以確定父范圍是否已更新?
預先感謝邁克爾
我相信您應該創建要附加在鏈接功能內的功能:
看一下這段代碼:
http://plnkr.co/edit/ZTx0xrOoQF3i93buJ279?p=preview
app.directive('clickToEdit', function () {
return {
templateUrl: 'clickToEdit.html',
restrict: 'A',
replace: true,
scope: {
value: '=clickToEdit',
method: '&onSave'
},
link: function(scope, element, attrs){
scope.save = function(){
console.log('save in link fired');
}
},
controller: function($scope, $attrs) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
console.log('save in controller fired');
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
$scope.method();
};
}
};
});
我以前沒有在控制器中聲明過函數,但是我不明白為什么它不起作用。
盡管此問題/答案對其進行了解釋鏈接vs編譯vs控制器
據我了解:
控制器用於在指令實例之間共享數據,而不是“鏈接”將作為回調運行的功能。
該方法正在被調用,但是angular沒有意識到它需要運行摘要循環來更新控制器范圍。 幸運的是,您仍然可以從隔離范圍內觸發摘要,只需包裝對方法的調用即可:
$scope.$apply($scope.method());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.