angularjs
  • angularjs-directive
  • 2016-03-04 54 views 0 likes 
    0

    我有將數據綁定到指令的這個奇怪的問題。這是我聲明我的指令:在指令中綁定數據會返回不一致的值

    <my-directive data="myArray"></my-directive> 
    

    我的指令代碼如下所示:

    angular.module('ngApp') 
    .directive('myDirective', function() { 
        return { 
         scope:{ 
          data: '=' 
         }, 
         template: '<div steps="data.length"></div>', 
         restrict: 'E', 
         link: function postLink(scope, element, attrs) { 
          console.log(scope); 
          console.log(scope.data); 
         } 
        }; 
    }); 
    

    中的第一個日誌,數據屬性是正確的: screenshot of console.log outputsecond log是不確定的。

    有什麼想法爲什麼?

    +0

    你能提供一個JSFiddle或Plunkr來演示這個問題嗎? – Matheno

    回答

    0

    這裏是您的解決方案:

    <my-directive data-example="myArray"></my-directive> 
    

    你應該總是命名變量data-<name>。這是更容易維護,這防止錯誤的關鍵字這樣一個;)

    angular.module('ngApp') 
    .directive('myDirective', function() { 
        return { 
         scope:{ 
          data: '=example' 
         }, 
         template: '<div steps="data.length"></div>', 
         restrict: 'E', 
         link: function postLink(scope, element, attrs) { 
          console.log(scope); 
          console.log(scope.data); 
         } 
        }; 
    }); 
    

    我希望這會幫助,

    活生生的例子:JsFiddle

    +0

    對不起,依然如此。如果你可以在這裏輸入完整的代碼,scope.data是undefined – Marcin

    0

    感謝@hadiJZ和@Unex我想通它出:

    我的指令嵌套在另一個指令。但是父指令使用邏輯的鏈接函數,因爲在創建時它沒有子指令。

    因此將邏輯移出到控制器解決了我的問題。 我想到了當我添加一個$超時到子指令,並且日誌(scope.data)是正確的。

    +0

    。謝謝 –

    相關問題