AngularJS没有解析来自ngRepeat的一些数据

时间:2017-07-20 09:14:05

标签: angularjs angularjs-directive angular2-template

HTML代码为:

<mydirective ui-if="isReady"></mydirective>

,指令代码为:

app.directive('mydirective', ['$http', '$window' ,'opt', function ($http, $window, opt) {

  return {
            strict: 'E',
            replace: false,
            transclude: true,
            templateUrl: opt.base_url + 'mytemplate',
            link: function(scope, element, attr) {
                $http({
                    url: opt.api_url + 'projects',
                    dataType: 'json',
                    method: 'GET',
                }).then(function (response) {
                    scope.projects = response.data;
                    scope.isReady = true;
                });
            },
  };
}]);

mytemplate返回此html代码:

<project ng-repeat="project in projects" projects="{{$scope.projects}}">
  <img ng-src="{{$project.owner.avatar_url}}">
  <h2>@{{project.name}}</h2>
</project>

Angular正确解析h2标签标题。问题是ng-src值根本没有解析并且包含文字{{$project.owner.avatar_url}}字符串。

结果:

<project ng-repeat="project in projects">
       <img ng-attr-src="{{$project.owner.avatar_url}}">
       <h2>Project #1</h2>
</project>

<project ng-repeat="project in projects">
       <img ng-attr-src="{{$project.owner.avatar_url}}">
       <h2>Project #2</h2>
</project>

知道造成这种奇怪行为的原因是什么?

谢谢。

1 个答案:

答案 0 :(得分:1)

为什么使用$project。只需使用project.owner.avatar_url

即可
 <img ng-src="{{project.owner.avatar_url}}">`

也不要使用html中的$scope

<project ng-repeat="project in projects" projects="{{projects}}">