[英]Access to scope in angular directive with two data bindigs
早上好我有一个小问题我有指令:
return {
restrict:'E',
scope: {
user: "="
},
template: '<b>{{userLogin}}</b>',
link:function(scope,elem,attrs){
},
controller: function ($scope) {
console.log($scope.user)//always undefindet
$scope.userLogin = $scope.user;
},
};
并且我想在模板中显示我的参数“user”和范围我必须使用控制器,因为我需要从服务器下载一些数据我认为问题在这里某处(在指令中):
scope: {
user: "=" //when i have this response "undefined"
user: "@" //when i have this response not show id only text
},
我的HTML
<get-user-login user="{{post.user_id}}"></get-user-login>
我总是得到:空值或在控制台中未定义。 如何解决这个问题。
使用@
,必须使用插值:
<get-user-login user="{{post.user_id}}"></get-user-login>
注意 @
仅适用于文本值
鉴于
使用=
您不需要插值
<get-user-login user="post.user_id"></get-user-login>
注意 =
仅用于传递对象(双向绑定)
我为你构建了这个演示,它运行得很好:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-controller="ctrl">
<get-user-login user="post.user_id"></get-user-login >
<script>
angular.module("app",[])
angular.module("app").
controller("ctrl",function($scope){
$scope.post = {user_id:565};
}).
directive('getUserLogin', function() {
return {
restrict:'E',
scope: {
user: "="
},
template: '<b>{{userLogin}}</b>',
link:function(scope,elem,attrs){
},
controller: function ($scope) {
console.log($scope.user)//always undefindet
$scope.userLogin = $scope.user;
},
};
});
</script>
</body>
</html>
你确定你给指令正确的价值吗? 因为在getPost中你将它绑定到$ scope.onePost,所以也许正确的方法是:
<get-user-login user="{{onePost.user_id}}"></get-user-login>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.