我有一个自定义指令。在链接函数的属性中,我试图获取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/