簡體   English   中英

Angular JS /數據綁定/控制器

[英]Angular JS / Data Binding / Controller

我有兩個控制器和一項服務。 有人可以解釋一下為什么姓氏不會更新/更改時引用是“舊的”嗎?

我以為這是控制器之間進行通信的方式...?

<!-- 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": ""                          
        },
                    ...
    }

在控制器之間進行通訊時,請檢查以下提示。

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/

<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'
    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM