質問

why is my code not working?

<div data-ng-app="app" class="container">
    <div>
        <div data-ng-controller="ControllerA"></div>
        <div data-ng-controller="ControllerB">
            <ul>
                <li data-ng-repeat="notify in notifications">{{notify}}</li>
            </ul>
        </div>

    </div>
</div>
<script>
var app = angular.module('app', []);
app.controller('ControllerA', ['$scope', 'Notification' , function ($scope, Notification) {
    var i = 0;
    Notification.set('Notification ' + i++);
    setTimeout(function () {
        $scope.$apply(function() {
            Notification.set('Notification ' + i++)
        })

    }, 2000)
}]);

app.controller('ControllerB', ['$scope'  , 'Notification', function ($scope, Notification) {
    $scope.notifications = Notification.notifications
    $scope.$watch('notifications', function () {
        console.log($scope.notifications)
    })
}]);

app.factory('Notification', function () {
    var notifications = [];

    return {
        notifications: notifications,
        set: function (name) {
            notifications.push(name);
            setTimeout(function () {
                notifications.shift();
                console.log(notifications)
            }, 5000)
            console.log(notifications)
        }
    }

});

A controllerA add in a factory "Notification" message that after some time should retire, it is removed in the factory, but does not appear in the controllerB changes.
Example here: http://jsfiddle.net/vivalaakam/vL8PC/4/

役に立ちましたか?

解決

Try using the $timeout service instead of setTimeout.

Also, calling $scope.$apply is mostly unnecessary.

var app = angular.module('app', []);

app.controller('ControllerA', ['$scope', '$timeout', 'Notification', 
    function ($scope, $timeout, Notification) {
        var i = 0;
        Notification.set('Notification ' + i++);
        $timeout(function () {
            Notification.set('Notification ' + i++)
        }, 2000);
    }
]);

app.controller('ControllerB', ['$scope', 'Notification', 
    function ($scope, Notification) {
        $scope.notifications = Notification.notifications;
        $scope.$watch('notifications', function () {
            console.log($scope.notifications);
        })
    }
]);

app.factory('Notification', ['$timeout',
    function ($timeout) {                         
        var notifications = [];
        return {
            notifications: notifications,
            set: function (name) {
                notifications.push(name);
                $timeout(function () {
                    notifications.shift();
                    console.log(notifications);
                }, 5000)
                console.log(notifications);
            }
        };
    }
]);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top