为什么在两个控制器中添加$ watch会破坏我的消化循环?

时间:2016-07-22 17:05:43

标签: angularjs

所以我知道如何解决我的问题。但我想首先理解为什么这是一个问题,所以我理解基本原理。

在我放置

时的以下Ajs代码中
$scope.$watch('city', function(){ //To watch for when the value changes on the FE and then changes when applicable.
       cityService.city = $scope.city;
});

在我的forecastCtrl中,它也破坏了我对城市变量的消化循环。这是为什么?我的FE是一个简单的文本输入,城市字段在主页上默认为纽约州纽约市。然后我的预测页面调用变量以使用字符串显示它。

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

    weatherApp.config(function($routeProvider) {
        $routeProvider

        .when('/', {
              templateUrl:'pages/home.htm',
              controller:'homeCtrl'
              })

        .when('/forecast', {
              templateUrl:'pages/forecast.htm',
              controller:'forecastCtrl'
              });
    });

    weatherApp.service('cityService', function(){
       this.city = 'New York, NY'; //Default variable

    });

    weatherApp.controller('homeCtrl', ['$scope', 'cityService', function($scope, cityService){
        $scope.city = cityService.city; //To introduce city to scope or else it wont be reconginzed in the controller.

        $scope.$watch('city', function(){ //To watch for when the value changes on the FE and then changes when applicable.
            cityService.city = $scope.city;
        });

    }]);

    weatherApp.controller('forecastCtrl', ['$scope', 'cityService', function($scope, cityService){
        $scope.city = cityService.city; //To introduce city to scope or else it wont be reconginzed in the controller.

    }]);

0 个答案:

没有答案