简体   繁体   中英

AngularJS - Pushing JSON data (structure correct, but something missing)

I'm completely new to AngularJS and I'm converting a small app at the moment, although there's one thing tripping me up.

My goal is to add a module to the dashboard and everything works correctly if I hardcode the JSON data, although, it seems to be having issues when using a variable.

My service:

var pushData = angular.toJson({"modID": "mod_rText_01", "sequence": 1, "group": 1, "dashboard": 1, "type": "text", "content": ["17%", "operating capacity"]});
console.log(' :: Module data pushed: ' + pushData);
$rootScope.$broadcast('locations', pushData); // broadcast to controller

My controller:

// listen for service location updates
$scope.$on('locations', function(event, pushData) {
    console.log(' :: Module data received: ' + pushData);
    $scope.locations.push(pushData);
});

Console logs:

:: Module data pushed: {"modID":"mod_rText_01","sequence":1,"group":1,"dashboard":1,"type":"text","content":["17%","operating capacity"]}
:: Module data received: {"modID":"mod_rText_01","sequence":1,"group":1,"dashboard":1,"type":"text","content":["17%","operating capacity"]}

As mentioned, if I change the controller line to be: $scope.locations.push({"modID":"mod_rText_01","sequence":1,"group":1,"dashboard":1,"type":"text","content":["17%","operating capacity"]});

It works correctly. I feel I'm missing something! Although, according to the console.log, the variable 'pushData' is correct, but nothing happens.

Any help will be greatly appreciated!

The problem is that you transform your object to JSON.

What you are doing here is you actually send a STRING , not an object.

angular.toJson({"modID": "mod_rText_01", "sequence": 1, "group": 1, "dashboard": 1, "type": "text", "content": ["17%", "operating capacity"]});

This string is being published in event and picked up in controller. So in below code, instead of an object, you are really adding a string to an array:

$scope.locations.push(pushData);

Solution: just publish regular JavaScript object instead of string and it should work as expected. $broadcast() and $on() are capable to work with real objects as well.

var dataObj = {"modID": "mod_rText_01", "sequence": 1, "group": 1, "dashboard": 1, "type": "text", "content": ["17%", "operating capacity"]};
$rootScope.$broadcast('locations', dataObj);

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