gpt4 book ai didi

javascript - Scope.attribute 可用但 scope.attribute.variable 在指令中未定义

转载 作者:行者123 更新时间:2023-11-30 05:40:57 24 4
gpt4 key购买 nike

我正在尝试一些 angularJS 开发,但我遇到了一个我根本不理解的问题。

我尝试将 JSON 格式化为具有许多规则的特定表。现在我的 JSON 看起来像:

{
"id":"test",
"title":"Test Sample",
"description":"Test Sample Description"
}

它被载入列表:

angular.module('myServices', ['ngResource'])
.factory('MyData', ['$resource',
function($resource){
return $resource('/rest/data', {}, {
getSample: {method:'GET', url:'/data/sample.json', isArray:false}
});
}
]);

angular.module('myControllers', ['myServices'])
.controller('DataController', ['$scope', 'MyData',
function($scope, MyData){
$scope.list = MyData.getSample(); //retrive a simple JSON
}
]);

然后我尝试重新排列数据:

<div id="list" data-ng-controller="DataController">   
<div data-table="view" data-list="list"></div>
</div>

现在是一个简单的指令:

angular.module('myDirectives', [])
.directives('table', function($timeout){
return {
restrict: 'A',
replace: true,
scope: { list : '='},
link: function(scope,$element, attrs){
console.log(scope);
console.log(scope.list);
console.log(scope.list.title);
}
};
});

但是 console.log() 中发生了什么:我有 scope :

$$asyncQueue: Array[0]
$$childHead: null
$$childTail: null
$$destroyed: false
$$isolateBindings: Object
$$listeners: Object
$$nextSibling: null
$$phase: null
$$postDigestQueue: Array[0]
$$prevSibling: null
$$watchers: Array[1]
$id: "007"
$parent: a
$root: h
list: Resource
this: h
__proto__: h

我有 scope.list(标记为 Resource):

$promise: Object
$resolved: true
description: "Test Sample Description"
id: "test"
title: "Test Sample"
__proto__: Resource

但是 scope.list.title 被标记为 undefined

我的搜索导致一些属性可能没有在链接处设置,但为什么 scope.list 仍然可用而不是它的属性?

我还尝试将 scope 设置为 truetable 指令中,但没有更好的结果

我要制作一个复杂的表格,所以我必须在这个 div 和表格中应用非常具体的规则。我不能简单地用一些 ng-If 来完成。

最佳答案

$scope.list 是一个 promise 。在您的情况下, promise 已经解决,因此 $resolved: true。但这仍然是一个 promise 。

来自ngResource docs :

$promise: the promise of the original server interaction that created this instance or collection.

On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

所以在 Angular 1.2+ 中,你想做这样的事情,在 promise 的 $promise 属性上使用 then 提供回调。一旦 promise 得到解决,回调将被调用并返回结果(在您的情况下,因为 promise 已经解决,回调将立即执行)。

link: function(scope,$element, attrs){
scope.list.$promise.then(function(results) {
console.log(results);
console.log("title ",results.title);
});
}

这是一个 working demo fiddle它使用 $httpbackend 来模拟服务器的响应。

关于javascript - Scope.attribute 可用但 scope.attribute.variable 在指令中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874274/

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