Answer the question
In order to leave comments, you need to log in
Binding directive model to service data that is loaded asynchronously
I'm trying to bind a custom directive model to the service data. The problem is that when the service data is updated by timeout or in the ajax request callback, the directive model is not updated.
Example: codepen.io/snater/pen/IjvFa
And code:
<div ng-app="asyncServiceTest" ng-controller="testController">
<bind-to-service></bind-to-service>
</div>
app = angular.module "asyncServiceTest", []
app.directive "bindToService", ["dataService", (dataService) ->
restrict: "E"
scope: {}
template: "<div>{{ test }}</div>"
link: (scope) ->
scope.test = dataService.test
]
app.factory "asyncService", ["dataService", "$timeout", (dataService, $timeout) ->
load: ->
dataService.test = "SYNC DATA!" # Works fine
$timeout ->
dataService.test = "ASYNC DATA!" # Doesn't work ((
, 2000
]
app.factory "dataService", ->
test: "Init Data"
app.controller "testController", ["$scope", "asyncService", ($scope, asyncService) ->
asyncService.load()
]
Answer the question
In order to leave comments, you need to log in
Everything became clear. The controller is launched before the directive, and at the time of initialization of the status model, dataService.test already contains the string “SYNC DATA!” (I thought that the binding worked). And the line "ASYNC DATA!" I didn’t write to the model because I tried to bind to a primitive, if dataService.test is an object, everything will work as expected.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question