我必须刷新页面以查看更改,Angular是双向绑定,但似乎我的问题它表现得像单向。我从1小时前就一直试图解决这个问题,但找不到任何解决办法。
的index.html
<div ng-controller="tweetController as tweet">
<form> <!-- USERNAME INPUT -->
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" ng-model="tweet.tweetData.title">
</div>
<!-- PASSWORD INPUT -->
<div class="form-group">
<label>Tweet Content</label>
<input type="text" class="form-control" ng-model="tweet.tweetData.content">
</div>
<!-- LOGIN BUTTON -->
<button ng-click= "tweet.createTweet()" type="submit" class="btn btn-block btn-primary">
<span>Create Tweet</span>
</button>
</form>
<tr ng-repeat="tw in tweet.tweets">
<td>{{ tw._id }}</td>
<td>{{ tw.title }}</td>
<td>{{ tw.content }}</td>
</tr>
</div>
tweetCtrl.js
angular.module('tweetCtrl', ['tweetService'])
.controller('tweetController', function(Tweet) {
var vm = this;
Tweet.all()
.success(function(data) {
vm.tweets = data;
});
vm.createTweet = function() {
vm.processing = true;
vm.message = '';
Tweet.create(vm.tweetData)
.success(function(data) {
vm.processing = false;
// clear the form
vm.tweetData = {}
vm.message = data.message;
});
};
});
service.js
angular.module('tweetService', [])
.factory('Tweet', function($http) {
// get all approach
var tweetFactory = {};
tweetFactory.all = function() {
return $http.get('/api/');
}
tweetFactory.create = function(tweetData) {
return $http.post('/api/', tweetData);
}
return tweetFactory;
});
答案 0 :(得分:0)
您需要将新的tweet
推送到您的tweets
收藏集 - 这不会自动更新。据我所知,您只需在页面加载时调用.all()
,因此只需在create
完成后推送到数组:
vm.createTweet = function() {
vm.processing = true;
vm.message = '';
Tweet.create(vm.tweetData)
.success(function(data) {
vm.processing = false;
// clear the form
vm.tweetData = {}
vm.message = data.message;
//show the new tweet in the view
vm.tweets.push(data); //assuming "data" is the returned tweet
});
};