gpt4 book ai didi

javascript - 使用父 Controller 的指令中的异步范围属性

转载 作者:行者123 更新时间:2023-11-29 17:10:11 25 4
gpt4 key购买 nike

仍在思考 angularJs,取得进展,但我不确定这个问题是与指令相关的误解还是更广泛的误解。

在我的 Angular 应用程序中,一个指令是从父指令 Controller 继承的(我的应用程序实际上并不像这样,但出于简单的 jsfiddle 的目的,它就是这样)。父 Controller 执行一些异步操作,我希望子模板相应地更新。

因此该属性是在子 Controller 完成其编译/链接过程后设置的。此属性已绑定(bind)到子模板,所以当它更新时为什么模板不更新?或者我需要做什么才能做到这一点?

正如我提到的,代码被大大简化了(异步位实际上是一个带有 $http 调用的服务,模板要复杂得多,我需要在中继器等中使用这个属性)但这本质上就是我的应用程序代码现在看起来像。

fiddle here

<div ng-app="myApp">
<dashboard>
<published></published>
</dashboard>
</div>

我的 Angular JavaScript

var app = angular.module('myApp', []);

app.directive('dashboard', function () {
return {
restrict: 'E',
controller: function ($scope) {
$scope.foo = '';

//this is actually to simulate an $http request
$scope.get = function () {
setTimeout(function() {
$scope.foo = "hello";
}, 1000);
};

$scope.get();

$scope.bar="world";
}
};
})
.directive('published', function ($compile) {
return {
restrict: 'E',
require: '^dashboard',
template : '<span>{{foo}} {{bar}}</span>',
link: function ($scope, element, attrs) {

console.log('scope', $scope); //can see foo in console so inheriting as expected
console.log('scope.foo', $scope.foo); //not there so obviously because of async
}
};
});

最佳答案

这是一个 fiddle :http://jsfiddle.net/967zF/

setTimeout 不要触发 $digest ,而是使用 $timeout:

app.directive('dashboard', function () {
return {
restrict: 'E',
controller: function ($scope,$timeout) {
$scope.foo = '';

$scope.get = function () {
$timeout(function() {
$scope.foo = "hello";
}, 1000);
};

$scope.get();

$scope.bar="world";
}
};
})

fiddle :http://jsfiddle.net/MP8DR/

或者,您也可以像这样触发一个 $digest:

setTimeout(function() {
$scope.$apply(function(){
$scope.foo = "hello";
});
}, 1000);

关于javascript - 使用父 Controller 的指令中的异步范围属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22096961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com