0

注意力

这个问题在这里被改写和回答:


我正在尝试使用 AngularsJS 指令。创建了一个简单的指令,但来自 $http 调用时 {{scopevars}} 不存在。例如:

控制器

function AppCtrl($scope, $routeParams, Card) {
    $scope.abc = "this works well";
    $scope.user = User.get({userId: 1}, function(user) {
      });
}

用户服务(运作良好)

angular.module('userServices', ['ngResource'])
    .factory('User', function ($resource) {
    return $resource('/user/:userId.json', {}, {
        query: {
            method: 'GET',
            params: {
                userId: 'user'
            },
            isArray: true
        }
    });
}

这是指令代码(已损坏):

/**
 * Create the <pretty-tag>{{var}}</pretty-tag>
 */
.directive('prettyTag', function($interpolate) {

return {
    restrict: 'E',
    link: function(scope, element, attrs) {
        var text = element.text();
        var e = $interpolate(text)(scope);
        var htmlText = "<b>" + e + "</b>";
        element.html(htmlText);
    }
};

结果:

// => In HTML view <pretty-tag>{{abc}}</pretty-tag> => <b>this works well</b>.
// => In HTML view <h1>{{user.name}}</h1> => <h1>Bob</h1>.
// => In HTML view <pretty-tag>{{user.name}}</pretty-tag> => Doesn't work (empty).

有人可以帮我理解为什么<pretty-tag>{{user.name}}</pretty-tag>通过 $http 调用设置的 var 不起作用吗?

4

3 回答 3

1

在工作的jsfiddle下面

http://jsfiddle.net/vishalvasani/cPVDn/10/

.directive('prettyTag', function($interpolate) {

return {
    restrict: 'E',
    link: function(scope, element, attrs) {
        var text = element.text();
        var e = $interpolate(text)(scope);
        // =============> problem e is always empty
        console.log(e)

        var htmlText = "<b>" + e + "</b>";
        element.html(htmlText);
    }
};
});
于 2013-08-19T10:59:10.840 回答
0

I think you need to assign the user value in the callback of the .get() method like this

User.get({userId: 1}, function(user) {
    $scope.user = user;
});

And you can pass the model user to the directive like this

<pretty-tag ng-model='user'></pretty-tag>

And inside the directive, access the text model via ngModel from attributes.

var text = attrs.ngModel;
于 2013-08-19T13:37:10.823 回答
0

link:函数中,尝试:

  $scope.$watch('user', function () {
    var text = element.text();
    var e = $interpolate(text)(scope);
    var htmlText = "<b>" + e + "</b>";
    element.html(htmlText);
  });

这是未经测试的,但看起来页面在 $http 调用返回数据之前呈现,因此 $scope.user 未定义。

于 2013-08-19T13:40:33.513 回答