我在一个更大的项目上遇到这个问题,我做了一个最简单的例子。
我有一个 Controller ,里面有一些数据。该数据被输入到指令中,并应使用 native ng-repeat 显示。然而,当指令 Controller 运行时,它还没有解析 Angular 变量,因此不会渲染重复。
如何使其工作,以便重复可以与需要预解析的外部变量一起使用?
这是一个 fiddle 。确保您已打开控制台,因为它显示该函数运行时未定义,但 1 秒后已定义:http://jsfiddle.net/paulocoelho/xqLAs/2/
这是我的 JS:
var module = angular.module('testApp', [])
.directive('test', function () {
return {
restrict: 'E',
template: '<p ng-repeat="x in sl">{{x.val}}</p>', // this wont work :(
scope: {
sl: '@sl'
},
link: function ($scope, $element, $attrs) {
console.log($attrs.sl); // this will return undefined
setTimeout(function(){
console.log($attrs.sl); // this will return the correct list
},1000);
}
};
});
function sweetCtrl($scope){
$scope.someList =
[
{"val":"a"},
{"val":"b"},
{"val":"c"},
{"val":"d"},
{"val":"e"},
{"val":"f"}
];
}
这是我的dom
<div ng-app="testApp" ng-controller="sweetCtrl">
<p>raw list: {{someList}}</p>
<p>repeat list:</p>
<test sl="{{someList}}"></test>
</div>
编辑: 我之前的代码中有一个错误,其中 inputdata 应读取 sl。
解决方案的摆弄在这里:http://jsfiddle.net/paulocoelho/xqLAs/3/
最佳答案
当您使用“@”时,结果始终是一个字符串。如果您将模板更改为显示 {{x}} 而不是 {{x.val}},您就会明白我的意思。
要将对象传递到隔离范围,请使用“=”:
<test sl="someList"></test>
template: '<p ng-repeat="x in sl">{{x.val}}</p>', // this will work :)
scope: {
sl: '='
},
此外,正如我(刚才)在您的 other question 中所解释的那样,当使用 '@' 时,您需要使用 $attrs.$observe 或 $scope.$watch() 异步获取值(这将是一个字符串)。使用“=”,您不必使用 $observe 或 $watch。
关于javascript - 如果数据更改,指令中的 ng-repeat 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15167779/