0

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.

2 Answers 2

2

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);
})
Sign up to request clarification or add additional context in comments.

8 Comments

Hi Mr.Helper,how can i use this data in my view?is it enough with this ng-model=data.city.name or i should call the function.
You can not directly use this data. You need to assign data to ng-modal eg. $scope.modalName = data;
How can i call this function $scope.$on('eventName',function(event,data){ console.log('data---',data); }) ?
Thanks Mr.Helper ,,,,,can you pls answer my question
Its not function, Its an event it will automatically get called once you broadcast event
|
0
app.controller('ctrl1',['$scope','$rootScope',function($scope,$rootScope) {
    $scope.xyz = $rootScope.xyz;
    //console.log($scope.xyz); hey
}]);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.