第一次更改后,无法使用工厂在控制器之间共享数据

时间:2015-09-18 18:02:04

标签: javascript angularjs javascript-events angularjs-directive angularjs-scope

我知道angularjs会进行双向数据绑定。我有两个控制器,我想互相交谈。我用工厂让他们互相沟通。在AppCtrl控制器中,我将Data.mydata.buildingName指定为等于名称。这就是我正在做的事情:

调用AppCtrl,并更改buildingName的值。

然后当我调用PathController时,它知道buildingName的值已经改变并显示它。

但是当我回到AppCtrl并再次更改buildingName的值时,PathController似乎并不知道这一点。

有谁能告诉我这里我做错了什么?

// factory

.factory('Data', function(){
    return { 
       mydata: {
           buildingName: 'Campus',
           shortName: 'Main',
           lattitude: '35.720031000963',
           longittude: '-87.343068987131'
       }
    };
})      

// controller one

.controller('AppCtrl', function($scope, Data, $http, $ionicModal, $timeout) {

    // map location
    $scope.mapLocation = function(name, shortName, lattitude, longittude) {
        Data.mydata.buildingName= name;
        Data.mydata.shortName= shortName;
        Data.mydata.lattitude= lattitude;
        Data.mydata.longittude = longittude
        $scope.Data = Data.mydata;

        console.log("From AppCtrl: " +  Data.mydata.buildingName+ "  "+ Data.mydata.shortName+"  "+ Data.mydata.lattitude + " "+ Data.mydata.longittude );
        $scope.modal.hide();
    }
})

// controller two

.controller("PathController", [ '$scope', 'Data', function($scope, Data) {

    $scope.Data = Data.mydata.buildingName;

    var name = Data.mydata.buildingName + " - " + Data.mydata.shortName;
    lattitude = Data.mydata.lattitude;
    longitude = Data.mydata.longittude;

    angular.extend($scope, {
        center: {
            lat: 35.720031000963,
            lng: -87.343068987131,
            zoom: 17
        },

        markers: {
           Campus: {
               lat: longitude,
               lng: lattitude,
               focus: true,
               draggable: false,
               message: name
           }, 
        },
    });
}])

1 个答案:

答案 0 :(得分:0)

PathController中,$scope.Datalattitudelongittudename只是字符串值。更改Data.mydata的属性不会影响它们。

观察更改值并相应更新控制器值的一种方法是使用$scope.$watch()

// add at the end of PathController
$scope.$watch(function () {
    return Data.mydata;
}, function (newValue) {
    $scope.Data = newValue.buildingName;
    $scope.markers.Campus.lat = newValue.lattitude;
    $scope.markers.Campus.long = newValue.longittude;
    $scope.markers.Campus.message = newValue.buildingName + " - " + newValue.shortName;
}, true /* check for object equality */);