我必须刷新 AngularJS 页面才能看到我的更改

I Have to refresh the AngularJS page to see my changes

我必须刷新页面才能看到更改,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;

});

您需要将新 tweet 推送到 tweets collection - 不会自动更新。据我所知,您只会在页面加载时调用 .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
        });
};