我正在使用內聯編輯進行表單編輯。 我在這裏找到一個例子: https://stackoverflow.com/a/16739227/169252使用角度繼承範圍進行內聯編輯 - 將表單提交給服務器
我適應了我的需要。 以下是一些代碼 (使用nodejs,express和jade)。 該指令:
// Inline edit directive
app.directive('inlineEdit', function($timeout) {
return {
scope: {
model: '=inlineEdit',
handleSave: '&onSave',
handleCancel: '&onCancel'
},
link: function(scope, elm, attr) {
var previousValue;
scope.edit = function() {
scope.editMode = true;
previousValue = scope.model;
$timeout(function() {
elm.find('input')[0].focus();
}, 0, false);
};
scope.save = function() {
scope.editMode = false;
scope.handleSave({value: scope.model});
};
scope.cancel = function() {
scope.editMode = false;
scope.model = previousValue;
scope.handleCancel({value: scope.model});
};
},
templateUrl: 'partials/inline-edit'
};
});
控制器:
div(class="inline_edit_div")
input(class="inline_edit_input" type="text" on-enter="save()" on-blur="cancel()" on-esc="cancel()" ng-model="model" ng-show="editMode")
span(ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false")
span(ng-hide="editMode" ng-click="edit()")
div(class="inline_edit_text")
{{model}}
和窗體本身:
div(ng-controller="MyCtrl")
form(id="user_form")
div.inline.action_buttons
button(class="buttons action_button" ng-click="save_user()") Save
div.info
div.element
label(class="form") Name
div.form(inline-edit="name")
div.element
label(class="form") Surname
div.form(inline-edit="surname")
div.info_element_bottom
label(class="form") Email
div.form(inline-edit="email")
myControllers.controller('MyCtrl', ['$scope', '$http',
function MyCtrl($scope, $http) {
$scope.name = "Name";
$scope.surname = "Surname";
$scope.email = "Email";
$scope.save_user = function() {
//What do I do here??
};
的指令( 'partials/inline-edit
')的模板
我的問題: 如此處所示, How do I submit a form to a controller on the server? 我可以在提交後發佈訪問$scope
的數據,例如, $scope.person
。
但是,使用inlineEdit指令,我創建了繼承的範圍 - 所以我一直無法弄清楚如何從我的控制器訪問我的表單數據。 https://stackoverflow.com/a/13428220/169252表示您無法從父範圍訪問子範圍。
簡而言之,如何用$ http提交整個表單(最好是我想了解如何在沒有傳統POST的情況下完成整頁重裝)?控制器中的$scope.save_user
被調用,但從那裏我不知道更多。形式
div.element
label(class="form") Name
div.form(inline-edit="user.name")
div.element
label(class="form") Surname
div.form(inline-edit="user.surname")
div.info_element_bottom
label(class="form") Email
div.form(inline-edit="user.email")
和控制器
$scope.user = {
names: 'Names',
surnames: 'Surnames',
email: 'Email'
};
然後:
$scope.save_user = function() {
$http.put('/save_user',$scope.user).success(function() {
alert("Callback!");
}).error(function() {
alert("Failed");
});
};
你實際上接收你發送的數據從'scope.handleSave({value:scope.model});'到' $ scope.save_user = function(data){/*data.value...*/}'。然後,您可以爲您的服務器執行常規'$ http.post('...',data)'。 – jpmorin
@jpmorin你是對的,但不處理保存只發送個別元素? – faboolous
我現在明白了。我錯過了閱讀。您在範圍中遇到的問題是您綁定到值(複製)而不是對象(引用)。如果你要發送一個像'$ scope.person = {name:'',surname:'',email:''}'這樣的對象,那麼雙向綁定就可以工作(變化也會發生在你的控制器中) 。但我明白你想在單個領域應用你的指令。我想你可能想改變你的做法。 – jpmorin