2013-07-16 104 views
1

我有两个控制器和一个服务。有人可以解释为什么 firstname将不会更新/参考是“旧”更改时?Angular JS /数据绑定/控制器

我认为这是控制器之间进行通信的方式......?

<!-- language: lang-js --> 
// Controller 1 
function controllerOne (..., myService) { 
    $scope.firstname = myService.customer.firstname; 
} 

// Controller 2 
function controllerTwo (..., myService) { 
    $scope.firstnameNew = myService.customer.firstname; 
} 

// Service 
application.factory('myService', ...) 
    function(...) { 
    return { 
     customer: { 
      "firstname": "", 
      "lastname": "", 
      "pers": "", 
      "street": "", 
      "zip": "", 
      "city": "", 
      "selectedCountry": "", 
      "comment": ""       
     }, 
        ... 
    } 
+1

请说明您的具体问题或添加额外的细节,突显正是你需要的。正如目前所写,很难确切地说出你在问什么。 – Stewie

回答

1

控制器之间通信,请检查下面的小提琴。

var myModule = angular.module('myModule', []); 
myModule.factory('mySharedService', function($rootScope) { 
    var sharedService = {}; 

    sharedService.message = ''; 

    sharedService.prepForBroadcast = function(msg) { 
     this.message = msg; 
     this.broadcastItem(); 
    }; 

    sharedService.broadcastItem = function() { 
     $rootScope.$broadcast('handleBroadcast'); 
    }; 

    return sharedService; 
}); 

function ControllerZero($scope, sharedService) { 
    $scope.handleClick = function(msg) { 
     sharedService.prepForBroadcast(msg); 
    }; 

    $scope.$on('handleBroadcast', function() { 
     $scope.message = sharedService.message; 
    });   
} 

function ControllerOne($scope, sharedService) { 
    $scope.$on('handleBroadcast', function() { 
     $scope.message = 'ONE: ' + sharedService.message; 
    });   
} 

function ControllerTwo($scope, sharedService) { 
    $scope.$on('handleBroadcast', function() { 
     $scope.message = 'TWO: ' + sharedService.message; 
    }); 
} 

ControllerZero.$inject = ['$scope', 'mySharedService'];   

ControllerOne.$inject = ['$scope', 'mySharedService']; 

ControllerTwo.$inject = ['$scope', 'mySharedService']; 

http://jsfiddle.net/simpulton/XqDxG/

0
<body data-ng-app="myApp">  
<div data-ng-controller="ctrl1"> 
     {{firstName}} 
     {{lastName}} 
    </div> 
     <div data-ng-controller="ctrl2"> 
     {{firstName}} 
     {{lastName}} 
    </div> 
</body> 
Script : 
     var myApp= angular.module('myApp', []); 
myApp.controller('ctrl1', function ($scope, myService) { 
    $scope.firstName = myService.firstName; 
    $scope.lastName = myService.lastName; 
    myService.firstName = "ABC"; 
    myService.lastName = "DEF"; 
}); 
myApp.controller('ctrl2', function ($scope, myService) { 
    $scope.firstName = myService.firstName; 
    $scope.lastName = myService.lastName; 
}); 
myApp.factory('myService', function ($rootScope) { 
    return { 
     firstName: '123', 
     lastName: '456' 
    }; 
});