我已将表单移动到mdDialog弹出窗口以获取用户输入以向页面添加帖子。
我关注了Angular Material的一个例子。到目前为止,它不会在表单填写后关闭对话框,反过来不会更新页面上的帖子列表:
我的控制器看起来像这样:
myApp.controller('PostsController', ['$scope', 'PostsService', '$mdDialog',
function ($scope, PostsService, $mdDialog) {
$scope.posts = PostsService.getPosts()
$scope.incrementUpvotes = function (post) {
post.upvotes += 1;
};
$scope.showAdd = function (ev) {
$mdDialog.show({
controller: DialogController,
scope: $scope,
template: '<md-dialog aria-label="Mango (Fruit)"> <md-content class="md-padding"><h1>Add a Post</h1> <form name="postForm" novalidate ng-submit="addPost()"> <div layout layout-sm="column"> <md-input-container flex> <label>Title</label> <input type="text" name="title"class="form-control" ng-model="newPost.title" ng-required> </md-input-container> </div> <div layout layout-sm="column"> <md-input-container flex> <label>Date</label> <input type="date" name="date" class="form-control" ng-model="newPost.date"> </md-input-container> <md-input-container flex> </div> <div layout layout-sm="column"> <md-input-container flex> <label>Link</label> <input type="url" class="form-control" ng-model="newPost.link"> </div> <div layout layout-sm="column"> <md-input-container flex> <label>Username</label> <input type="text" name="username"class="form-control" ng-model="newPost.username" ng-required> </div> </md-input-container> </form> </md-content> <div class="md-actions" layout="row"> <span flex></span> <md-button type="submit" class="btn btn-primary" ng-click="addPost()" ng-disabled="postForm.$pristine || (postForm.$dirty && postForm.$invalid) "> Post </md-button></div> </md-dialog>'
,
targetEvent: ev
});
};
}]);
function DialogController($scope, $mdDialog) {
$scope.addPost = function () {
$mdDialog.addPost.then(function () {
var new_id = 1 + $scope.posts[$scope.posts.length - 1].id
$scope.posts.push({
title: $scope.newPost.title,
id: new_id,
link: $scope.newPost.link,
username: $scope.newPost.username,
comments: [],
upvotes: 0
});
$scope.newPost = {};
$mdDialog.hide();
});
};
};
在我的视图中调用它的html如下:
<md-button class="md-fab md-fab-bottom-right" aria-label="Add" ng-click="showAdd($event)">
<ng-md-icon icon="add"></ng-md-icon>
</md-button>
在过去的几个小时里,我一直在玩这个,无法解决这个问题,我们将非常感激任何见解。
答案 0 :(得分:3)
你做错了我的朋友。当您在$mdDialog
中调用.hide()
方法时,DialogController
会返回承诺。因此,将对象作为参数传递并捕获它为.then
,因为它会撤消承诺并使用该对象推送到$scope.posts
对象。
请参阅以下示例了解wokring演示。 http://codepen.io/next1/pen/ONWzrE