I have the problem that my variable $scope.test
is continuously changing.
First I have a function on my node.js server, which returns a json object like the one below:
{
objectOne: "some text",
objectTwo: "more text",
objectThree: {
text: "important text",
inf: "some info"
},
objectFour: "even more text"
}
then in angular i have a controller. (This controller is used for 2 html templates. not sure if important). So to the function in the controller:
$scope.start = function () {
$location.path('/start');
SomeService.start({}, someVar, function (success, msg, t) {
if (!success) {
console.error(msg);
}
$scope.test = t;
console.log($scope.test); //this prints out the json object above
});
};
And then I have a template file test.html:
<div>
<md-card>
<md-card-title>
<md-card-title-text>
<span class="md-headline">{{test.objectThree.text}}</span>
</md-card-title-text>
</md-card-title>
<md-card-actions layout="row" layout-align="end center">
<md-button>Cancel</md-button>
</md-card-actions>
</md-card>
</div>
The problem is that it doesn't display the text. So I made another function in the controller which logs the $scope.test
every 100ms.
$interval(function () {
console.log($scope.test);
}, 100);
The strange thing now is that it prints out like the following example:
Object {
objectOne: "some text",
objectTwo: "more text",
objectThree: {
text: "important text",
inf: "some info"
},
objectFour: "even more text"
}
--
undefined
--
undefined
And this continues. once it prints out the object, then 2 times undefined.
BUT when I define a vairable $scope.test2 = "test2text"
OUTSIDE of the function and then have my html like this:
<div>
<md-card>
<md-card-title>
<md-card-title-text>
<span class="md-headline">{{test2}}</span>
</md-card-title-text>
</md-card-title>
<md-card-actions layout="row" layout-align="end center">
<md-button>Cancel</md-button>
</md-card-actions>
</md-card>
</div>
it works and displays the text on the site but I don't have any idea why.
So does anyone has an idea why it is like that? If you need additional information just ask. Thank you for taking the time ;)
Don't pass the $scope
around, it is something really tricky and can be confusing.
You can however use a service
to provide functions
to your controller and use it from there.