javascript - Angular 指令 - 异步 attr 插值

标签 javascript angularjs

我有一个自定义指令。在链接函数的属性中,我试图获取attributes.user;的值。在我的 View 页面中,此自定义指令按以下方式使用:

<div my-directive user="{{user.name}}"></div>

现在 user 是一个模型对象,我在使用 $http 服务向某个 url 发出请求后从 JSON 响应中返回该对象。但是,当我通过在代码中插入“调试器”来检查指令中 attribute.user 的值时,attribute.user 为空白。如果我将 user.name 设置为“hello”之类的内容,我实际上会得到“hello”。我也尝试过:

attributes.$observe('user', function(val){...})

但无济于事。这是因为我正在发出异步请求,这就是我得到空白的原因吗?这是怎么回事?我该如何解决这个问题?谢谢!

编辑:这是我的指令代码片段

angular.module('myApp').directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: true,
    link: function($scope, elem, attr) {
      $scope.user = $.parseJSON(attr.user)
    },
    controller: ['$scope', '$rootScope', 'GlobalVariables', function($scope, $rootScope, GlobalVariables) {

    $rootScope.hasSignedUp = GlobalVariables.hasSignedUp;
    $rootScope.signUpId = GlobalVariables.signUpId;

    $rootScope.$watch('hasVoted', function(newVal, oldVal) {
      if(newVal === true) {
        if($rootScope.signUpId == $scope.user.id){
          $scope.text = 'Signed Up!';
        }else{
          $scope.text = 'Sign Up';
        }
      }else{
        $scope.text = 'Sign Up';
      }
     });
    }]
  };
});

最佳答案

首先,scope 不应该是 bool 值,而是包含您期望的属性键的字典,将 scope 更改为:

scope: {
    user: '=',
}

此外,目录期望范围值是变量并且不包含 Angular Handlebars 。这是正确的做法:

<div my-directive user="user"></div>

现在应该可以了。请参阅AngularJS's documentation了解更多信息。

关于javascript - Angular 指令 - 异步 attr 插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858366/

相关文章:

javascript - Angular : get coordinates of table row

javascript - 审查员无法批准我的 Tizen 应用程序,因为他们无法在我的应用程序播放器中播放 HLS

javascript - 在 Angular 中输出第 3 列和第 5 列的总数之差

javascript - 使用 AngularJS 使用 Java REST 服务(更新、删除问题)

javascript - RxJS Observable.fromEvent 数据

javascript - 如何使用mongodb删除数组内的对象,数组内的对象

javascript - 将信息传递到 Google 文档附加组件中的服务器端功能

javascript - 针对 Grails 后端的 PhoneGap 身份验证模式

javascript - Angular : using $http without $scope

AngularJS Microsoft Edge 屏幕不反射(reflect) DOM