简体   繁体   中英

How to use rootScope in angularjs

I have a data in my commonservice and I want to use the data in my template and I will assign a rootscope and use it but it isn't working right now and I am not sure what's wrong can anyone please suggest help.

My js:

function addGoogleAddress(id, data, scope) {
    var places = new google.maps.places.Autocomplete(document.getElementById(id));
    google.maps.event.addListener(places, 'place_changed', function () {
        var place = places.getPlace();
        if (place && place.address_components) {
            for (var i = 0; i < (place.address_components.length); i++) {
                if (place.address_components[i].types[0] === 'locality') {
                    data.city.key = '1001';
                    data.city.name = place.address_components[i].long_name.toString();
                } else if (place.address_components[i].types[0] === 'administrative_area_level_1') {
                    data.state.key = '1001';
                    data.state.name = place.address_components[i].long_name.toString();
                } else if (place.address_components[i].types[0] === 'country') {
                    data.country.key = '1001';
                    data.country.name = place.address_components[i].long_name.toString();
                }
            }
        }
    });
    $timeout(function () {
        $('#' + id).removeAttr('placeholder');
    }, 500);
    $rootScope.data = data;
}

My controller:

  console.log($rootScope.data)

Here i am getting undefined.

You can not broadcast data directly, you need to broadcast event and pass parameter like follows,

Note: I am assuming here you have injected dependency

 $rootScope.$broadcast('eventName',data);

Then in controller like follows -

$scope.$on('eventName',function(event,data){
console.log('data---',data);
})
app.controller('ctrl1',['$scope','$rootScope',function($scope,$rootScope) {
    $scope.xyz = $rootScope.xyz;
    //console.log($scope.xyz); hey
}]);

app.run(function($rootScope){
    $rootScope.xyz ="hey";
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM