2013-08-06 39 views
0

這裏添加範圍不工作href是我的html:Angularjs:當我的指令

<a href="#modal{{screencast.id}}" role="button" class=" btn" data-toggle="modal" 
      ng-click="fetch_comments(screencast.id)" ng-video url="match_url(screencast.video_url)">Play</a> 

我的指令:

'use strict'; 

App.directive('ngVideo', [function() { 
return { 
    restrict: 'A', 
    scope: { url: '='}, 

    link: function (scope, elem, attrs) { 
     elem.bind('click', function() { 
      console.log(scope.url); 
     }); 
    } 
    } 
}]); 

當我刷新頁面href="#modal{{screencast.id}}"我只有href="#modal"。當我從指令中刪除scope: { url: '='}時,它工作正常,並且href的值爲screencast.id。 我做錯了什麼?

回答

1

我打算假設你發佈的HTML代碼段被放置在一個ng-video元素中(在你的消息中不明確,但是你描述的內容似乎表明了這一點)。

當您將scope: { url: '='}添加到您的指令中時,將創建一個隔離範圍,這意味着將創建一個新範圍,並且此指令中的所有元素都將位於此新範圍內,與父範圍斷開連接。在這種情況下,您的{{screencast.id}}綁定將無法訪問截屏視圖對象,如果它位於父範圍內。

我認爲,針對您的情況,最好的解決方案是刪除scope: { url: '='},因爲您只是使用它來讀取單個屬性,而是使用attrs參數。

你的鏈接功能可能看起來像:

link: function (scope, elem, attrs) { 
    var urlAttr; 
    //watch url attribute (we have to wait for the binding to be evaluated, hence the $observe) 
    attrs.$observe('ngModel', function(value) { 
     urlAttr = value; 
    }); 
    elem.bind('click', function() { 
     if(urlAttr){ 
      console.log(urlAttr); 
     } 
    }); 
} 
+0

感謝晏,它爲我工作。 –