ivan ivan - 2 months ago 11
JSON Question

$scope is not refreshing after value changed

I have service module which read JSON file and returns JSON data.
Here is code

angular.module('serviceModule').service('dataService',["$http",function($http){
return {
getData:function(file){
return $http.get('url to json file').then(function(response) {

return response.data;
});
}


I am getting this data in my directive and assigning it to my $scope variable.

angular.module('xyz').directive('xyz',function(dataService){
return {
templateUrl:'hfhf',
controller:'hgf',
link:function($scope){
console.log("Hi");

$scope.tasks=[];
dataService.getData('location to json file').then(function(data){
$scope.tasks=data;
});


so my main problem is I have another controller which is changing value at 'location to JSON value',but this change is not reflecting immediately when I refresh the web page then only those change are reflecting.
I have tried implementing with watcher but it throws ERROR continuously and my browser becomes unresponsive.
Can anyone please help me to reflect changes immediately when change happens in 'location to JSON value'

My HTML directive as asked by some of you .In directive, i am doing

<div ng-repeat='task in tasks track by $index' class="xyzwell"data-jqyoui-options="{revert: 'invalid'}" data-drag="true" jqyoui-draggable="{index: {{$index}},placeholder:'true', animate: true,onStop:'dragStopCall()'}" id='{{$index}}' >
<div class="editIcon " >

<div class="pull-right">
<i class="fa fa-cog"></i>
<i class="fa fa-trash" aria-hidden="true"></i>
</div>
</div>
<div class="taskDetailarea">
<p>{{$index}} {{dragStopCall}}</p>
<p>{{task.xy}}</p>
<p>{{task.abc}}</p>
<p>{{task.bcd}}</p>
</div>



Here I am using ngDragDrop thats why I have added those tags those are working fine.I am just iterating through tasks thats all.

Answer

As asked, I am posting my comment as an answer since it worked for the OP.

I am not sure if I completely understand your issue, but take a look at $broadcast/$emit and $on. When your controller makes a change, publish a message with $broadcast or $emit, and then wire up your directive to listen for that event using $on. Here is a great SO link: Working with $scope.$emit and .$on

I'll borrow from the link to give an overview here as well:

$broadcast -- dispatches the event downwards to all child scopes

$emit -- dispatches the event upwards through the scope hierarchy.

So a quick example of the usage would be:

function firstCtrl($scope)
{
    $scope.$broadcast('someEvent', [1,2,3]);
}

function secondCtrl($scope)
{
    $scope.$on('someEvent', function(event, mass) { console.log(mass); });
}
Comments