2015-06-24 93 views
0

我有一個變量,我想通過範圍傳遞給我的指令,然後在鏈接中使用該變量(如果可能的話)。我是相當新的使用指令,有些事情對我來說有點模糊。這是我當前的代碼通過範圍將變量傳遞給指令angularjs

.directive('imagesFormat', function($cordovaCamera, $ionicModal, $cordovaFile, $cordovaFileTransfer) { 
     return { 
     restrict: 'EA', 
     scope: { 
      datasource: '&', 
     }, 
     link: function(scope, element, attrs) { 
      element.bind("click", function() { 
      if(attrs.imagesFormat === "takePhoto") { 
       var options = { 
       destinationType : Camera.DestinationType.FILE_URI, 
       sourceType : Camera.PictureSourceType.CAMERA, 
       allowEdit : false, 
       encodingType: Camera.EncodingType.JPEG, 
       popoverOptions: CameraPopoverOptions, 
       correctOrientation: true 
       }; 
      } 
      if(attrs.imagesFormat === "choosePhoto") { 
       var options = { 
       destinationType : Camera.DestinationType.FILE_URI, 
       sourceType : Camera.PictureSourceType.PHOTOLIBRARY, 
       allowEdit : false, 
       encodingType: Camera.EncodingType.JPEG, 
       popoverOptions: CameraPopoverOptions, 
       mediaType: Camera.MediaType.PICTURE, 
       correctOrientation: true 
       }; 
      } 
      scope.activeSlide = scope.datasource; 
     }); 
     } 
    } 
    }) 

我的HTML代碼

<ion-content overflow-scroll='false'> 
     <div class= "row"> 
     <div class="col"> 
     <button images-format="takePhoto" datasource="$index">Take Photo</button> 
     </div> 
     <div class="col"> 
     <button images-format="choosePhoto" datasource="$index">Image Gallery/File</button> 
     </div> 
     </div> 
    </ion-content> 

所以基本上我希望能夠在我的指令,得到的是$index值並將其分配給scope.activeSlide = scope.datasource多數民衆贊成

+0

數據源: '&',和用於功能varible use「=」 – PavanAsTechie

+0

$ index從哪裏來?它是一個自定義函數,變量或字符串,你在你的範圍設置?還是來自一個角度指令,如ng-repeat? –

回答

1

通過將範圍添加到指令中,我們創建了「隔離範圍」。通過這種方法範圍可以通過3種方式獲取屬性:

  1. @捕獲從DOM作爲字符串值的屬性值。
  2. =將屬性評估爲父作用域的屬性。
  3. &將屬性評估爲父作用域的方法。

你可以閱讀更多關於它在這裏:根據您的例子

http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/

上面看來,你需要一個=

restrict: 'EA', 
     scope: { 
      datasource: '=', 
     }, 
+0

'datasource:'= $ index','這是錯誤的。這意味着數據源預計將從稱爲$ index的DOM屬性(例如, '

+1

這是迄今爲止我所見過的關於@,=和指令細目的最清晰的方法。 – mikeswright49

0
scope: { 
    datasource: '&', 
} 

更改&通過這樣做,你可以說你期望數據源被綁定到一個有效的位置函數指針。如果這是你所需要的,那很好。 但是,如果要綁定到變量/表達式,請使用'=',或者如果要綁定到字符串,請使用'@'

其他一些問題。

你似乎只是然後使用datasource設置一個新的範圍變量(新的,因爲你現在有一個孤立的範圍工作):

scope.activeSlide = scope.datasource;

這從它的外觀是多餘的。你可以簡單地引用scope.datasource而不是你需要它,而不是基本上在這個階段創建什麼是重複的。

其次,您通過使用attrs供應商訪問imagesFormat,這很好...但請注意您可能也有這上範圍定義:

scope: { 
    datasource: '&', 
    imagesFormat: '@' 
} 

,然後使用:

<button images-format="takePhoto" datasource="$index">Take Photo</button> 

if(scope.imagesFormat === "takePhoto") 
相關問題