我从角种子开始了一个项目。我将其与另一个具有jQuery的项目混合。我无法在模板中访问范围变量。
JS:
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope', function ($scope) {
$scope.showView = true;
$scope.proBlock = false;
$scope.modelBlock = false;
$.when(dbReadyDeferred).then(function() {
$scope.proBlock = true;
console.log('dbReadyDeferred.state()',dbReadyDeferred.state());
});
...
HTML:
<div ng-show="showView">
{{proBlock}}
</div>
在浏览器中,它显示:false
。我的代码有问题吗?
谢谢
如果您确定$.when(dbReadyDeferred).then(function() {})
正在调用您的函数,请按如下所示更改控制器代码:
.controller('View1Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.showView = true;
$scope.proBlock = false;
$scope.modelBlock = false;
$.when(dbReadyDeferred).then(function() {
$timeout(function() {
$scope.proBlock = true;
console.log('dbReadyDeferred.state()',dbReadyDeferred.state());
});
});
}]);
因为,您正在$scope.proBlock
使用jQuery更改值,所以Angular不会意识到这一更改,因此我们需要明确地告诉Angular运行摘要周期。
我们也可以使用$scope.$apply()
,但是将调用包装到$timeout
函数中是一种更干净的方法。
阅读更多:带有Ajax表单提交的AngularJS需要单击两次
更新:
您可以这样修改您的resolve变量:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'.
resolve: {
dbState: ['$rootScope', '$q', function($rootScope, $q) {
var promise = $q.when(dbReadyDeferred)
promise.then(function() {
$rootScope.$broadcast("dbStateReady");
});
return promise;
}]
}
});
}])
.controller('View1Ctrl', ['$scope', function ($scope) {
$scope.showView = true;
$scope.proBlock = false;
$scope.modelBlock = false;
var deregisterFunction = $scope.$on("dbStateReady", function() {
$scope.proBlock = true;
console.log('dbReadyDeferred.state()',dbReadyDeferred.state());
deregisterFunction(); // Remove this watch for $on listener
});
});
基本上,我们将$q.when
(如提到的@shushanthp)移至resolve
并使用,$broadcast
以了解何时可以使用db状态$on
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句