AngularJS - 更改路径时范围不刷新

时间:2014-07-07 14:32:16

标签: angularjs angularjs-scope

首先抱歉主题名称,我不知道怎么称呼它。我正在寻找答案,但没有发现任何有用或不知道如何在我的小应用程序中实现这一点。我正在学习AngularJS,我认为一个“饮料柜台”将有利于开始。所以我的所有应用程序都要做的就是当你点击一个饮料图标时它会添加一个项目(饮料的类型和日期时间),而问题是当我改变路径到#archive / it时它没有刷新饮料列表只有当我刷新页面时,我的代码是:

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

myApp.config(function ($routeProvider) {
    $routeProvider
        .when('/',
            {
                controller: 'myController',
                templateUrl: 'Views/home.html'
            })
        .when('/archive',
            {
                controller: 'myController',
                templateUrl: 'Views/archive.html'
            })
        .otherwise({ redirectTo: '/' });
});

myApp.factory('myFactory', function () {
    var saved = localStorage.getItem('myData');
    var drinks = (localStorage.getItem('myData') !== null) ? JSON.parse(saved) : [];

    localStorage.setItem('myData', JSON.stringify(drinks));

    var factory = {};
    factory.getDrinks = function () {
        return drinks;
    };

    return factory;
});

var controllers = {};
controllers.myController = function ($scope, myFactory, $filter) {
    $scope.drinks = [];

    init();

    function init() {

        $scope.drinks = myFactory.getDrinks();

        $scope.beerDrinked = $filter('filter')($scope.drinks, 'beer').length;
    }

    $scope.nowDrinking = function (what) {
        $scope.drinks.push({
            drinkDate: new Date(),
            what: what
        });

        localStorage.setItem('myData', JSON.stringify($scope.drinks));
    };
}
myApp.controller(controllers);

是的,当然。这是我的存档HTML:

<ul class="drinked" data-ng-repeat="drink in drinks | orderBy: 'drinkDate':true track by $index">
    <li class="{{ drink.what }}"><span class="date">{{ drink.drinkDate | date: 'EEEE, d MMMM yyyy' }}</span><span class="time">{{ drink.drinkDate | date: 'HH:mm:ss'}}</span></li>
</ul>

这是在家里:

<span data-ng-bind="beerDrinked"></span>
<a href="#" class="btn-drink" data-ng-click="nowDrinkig('beer')">beer</a>

2 个答案:

答案 0 :(得分:0)

如果你想刷新你的html,你要使用ng-repeat,例如:

<div class="drinks" data-ng-repeat="drink in drinks"></div>

我不知道用户必须点击哪些内容来刷新您的页面,但要做到这一点,您需要使用data-ng-click指令,例如:

<button data-ng-click="addDrink(someDrink)"></button>

所以在你的控制器中应该是这样的,例如:

app.controller('MyController', function ($scope) {
   $scope.drinks = [];
   $scope.addDrink= function (drink) { //note that you don´t need(and don´t should) to pass your drink by parameter...
      $scope.drinks.push(drink);
   }

});

答案 1 :(得分:0)

这里,将你的ng-repeat放在li元素中,如下所示:

<ul class="drinked">
    <li data-ng-repeat="drink in drinks | orderBy: 'drinkDate':true track by $index" class="{{ drink.what }}"><span class="date">{{ drink.drinkDate | date: 'EEEE, d MMMM yyyy' }}</span><span class="time">{{ drink.drinkDate | date: 'HH:mm:ss'}}</span></li>
</ul>

试试吧!