简体   繁体   中英

Access to scope in angular directive with two data bindigs

good morning i have a small problem i have directive:

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;
        },
    };

and i want to show my parameter "user" with scope in template i must use controller because i need download some data from server I think problem is somewhere here(in directive):

scope: {
                user: "=" //when i have this response "undefined"
                user: "@" //when i have this response not show id only text
            },

my HTML

<get-user-login user="{{post.user_id}}"></get-user-login>

i always getting: empty value or undefined in console. How to fix that.

When using @ you have to use interpolation as:

<get-user-login user="{{post.user_id}}"></get-user-login>

Note @ is ONLY for text values

WHEREAS

When using = you do not need interpolation

<get-user-login user="post.user_id"></get-user-login>

Note = is only for passing objects (two way binded)

I built this demo for you and it works just fine :

<!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>

Are you sure that you're giving correct value to directive? Because in getPost you're binding it to $scope.onePost, so maybe correct way is:

<get-user-login user="{{onePost.user_id}}"></get-user-login>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM