簡體   English   中英

使用兩個數據綁定訪問angular指令中的范圍

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM