2017-03-07 68 views
1

早上好,我有一個小問題,我有指令:訪問的角度指令範圍內有兩個數據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; 
     }, 
    }; 

,我想表明我的參數「用戶」與範圍,模板我必須使用控制器,因爲我需要從服務器下載 一些數據,我認爲問題是某處這裏(指令):

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> 

我總是得到:空值或在控制檯中未定義。 如何解決這個問題。

+0

檢查'@'和'='之間的區別(http://stackoverflow.com/questions/ 14050195 /什麼是在指令範圍內的角度js?rq = 1) –

回答

0

當使用@你必須使用插值:

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

注意@只用於文本值

鑑於

當使用=你不需要插值

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

注意=僅用於傳遞對象(綁定雙向)

+0

仍未定義 – Kaker

+0

請粘貼您的控制器代碼,您傳遞給指令的值被定義。 –

+0

Kaker

0

我建立這個演示爲你和它工作得很好:

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

你確定你給正確的值指示?因爲在getPost中,你將它綁定到$ scope.onePost,所以也許正確的方法是:

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