我正在尝试做简单的事情 - 将指令的模型绑定到服务的数据。并且在服务的数据异步加载之前(通过 $timeout 或 $http 请求),它根本不会更新指令的模型。
实时示例http://codepen.io/snater/pen/IjvFa
和来源:
<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()
]
在 asyncService 中调用 $rootScope 上的 $apply 不起作用,这是意料之中的,但我已经尝试过了。