Reputation: 458
I'm very new to AngularJs and I have simple question. I want to put the name. But this name has one value at first but after 0.3-0.5 sec it have other value. I don't know how to bind it, that the value could change.
HTML code:
<div ng-controller="FormController">
<h2 >
{{getName()}}<br>
<span class="icon-f-gear"></span>
<small>Procesas</small>
</h2>
</div>
Angular controller:
var App = angular.module('form', ['ui.bootstrap']);
App.controller('FormController', ['$scope' ,'$http', function($scope, $http) {
$scope.tasks = [];
$scope.socket.stomp.subscribe("/app/tasks", function (message) {
if ($scope.tasks.length !=0){
$scope.tasks.removeAll();
}
JSON.parse(message.body).forEach(function (el) {
$scope.tasks.push(el);
});
});
$scope.getName = function(){
return $scope.tasks[0].form.name;
};
I'm using Stomp protocol, it gives me data not instantly, because it has to send request to server and get it back, it takes time. I tried to debug after the request variable $scope.tasks[0].form.name changes from undefined to "Institution", but in the screen undefined stays, how to bind variable to change the value dinamically. Thanks for help in advance!
UPDATE Problem solved, I just had to use $scope.apply(...) function. Code here:
var App = angular.module('form', ['ui.bootstrap']);
App.controller('FormController', ['$scope' ,'$http', function($scope, $http) {
$scope.tasks = [];
$scope.socket.stomp.subscribe("/app/tasks", function (message) {
if ($scope.tasks.length !=0){
$scope.tasks.removeAll();
}
JSON.parse(message.body).forEach(function (el) {
$scope.tasks.push(el);
});
$scope.apply(function(){$scope.tasks});
});
$scope.getName = function(){
return $scope.tasks[0].form.name;
};
Thanks for help!
Upvotes: 0
Views: 3997
Reputation: 11
I believe the method you are calling returns undefined, because it has no data. In other words: give it an initial value, and it should work
I would rewrite it to:
<div ng-controller="FormController">
<h2>
{{formName}}<br>
<span class="icon-f-gear"></span>
<small>Procesas</small>
</h2>
</div>
And
App.controller('FormController', ['$scope' ,'$http', function($scope, $http) {
$scope.formName = '';
--- rest of code
Or, if you wish to keep it in the current way: App.controller('FormController', ['$scope' ,'$http', function($scope, $http) {
$scope.tasks = [];
$scope.tasks[0].form.name = '';
or
$scope.getName = function(){
return ($scope.tasks.length > 0) ? $scope.tasks[0].form.name : '';
};
I hope this helps
Upvotes: 0
Reputation: 42669
Most probably the subscribe callback is not being called in angular context. Try to wrap the callback code in $scope.$apply
and see if it works
$scope.socket.stomp.subscribe("/app/tasks", function (message) {
$scope.$apply(function() {
if ($scope.tasks.length !=0){
$scope.tasks.removeAll();
}
JSON.parse(message.body).forEach(function (el) {
$scope.tasks.push(el);
});
});
});
Upvotes: 3