2014-12-25 64 views
3

我一直在開發一個AngularJS指令,它應該作爲一個獨立的小部件工作,它可以通過設置對象形式的屬性進行配置。我的主要目標如下:將動態數據傳遞給angularjs指令的正確方法

  1. 根據在屬性中傳入的對象執行內部指令的處理。處理確實涉及獲取REST API響應。所以我正在使用控制器來實現這一點。
  2. 在我的指令做了一些處理之後,它可能會更改我的父控制器應該能夠更改的對象。

下面是覆蓋我的目標的示例代碼。

指令用法:

<post-listing page-id="currentPage.id" config="postConfig" posts="posts" /> 

代碼指令

'use strict'; 

angular.module('myApp') 
    .directive('postListing', function() { 
     return { 
      templateUrl: '/views/directive.post-listing.html', 
      restrict: 'EA', 
      scope: { 
       page_id:"=", 
       config:"=", 
       posts:"=", 
      }, 
      controller: "DirectivePostListingCtrl" 

     }; 
    }); 

代碼指令的控制器:

​​

代碼模板:

<h4>Displaying Posts for {{page.title}}</h4> 
<ul> 
    <li ng-repeat="p in posts" >{{p.title}}</li> 
</ul> 

當我運行此代碼時,它說$ scope.page_id要麼是「undefined」要麼是它說「currentPage.id」(基於運算符selected =或@),我希望它是currentPage.id。

請建議。

在此先感謝。

+0

您應該爲'$ scope.page_id'嘗試'$ watch'一次,我相信這些會使用某些服務。所以當控制器初始化時它不可用。或者你可以使用'$ broadcast'。 – Satpal

+0

你能列出控制器中的代碼如何訪問page_id和config嗎? – elaijuh

回答

4

對於隔離的作用域屬性名稱,您沒有遵循camelCase命名規則。您將能夠訪問頁ID,如果您使用此配置:

scope: { 
    pageId: "=", 
    config: "=", 
    posts: "=", 
}, 

和控制器:

console.log($scope.pageId); 
0
<post-listing data="PostListing" /> 

//使用這個是控制器

'use strict'; 

angular.module('myApp') 
    .controller('DirectivePostListingCtrl', function ($scope, $rootScope, $routeParams) 
    { 
     $scope.PostListing={} 
     $scope.PostListing.pageId=//Your Data 
     $scope.PostListing.config=//Your Data 
     $scope.PostListing.posts=//Your Data 
    }); 

製作您的指令變更

angular.module('myApp') 
    .directive('postListing', function() { 
     return { 
      templateUrl: '/views/directive.post-listing.html', 
      restrict: 'EA', 
      scope: { 
       data:"=" 
      }, 
      controller: "DirectivePostListingCtrl" 

     }; 
    }); 
012在模板

使用如下代碼

<ul> 
    <li ng-repeat="p in data.posts" >{{p.title}}</li> 
</ul> 
0

三個主要問題

  1. 與@,屬性必須是評價值。所以在屬性中應該是這樣的:page-id="{{currentPage.id}}"。在這裏看到更好的解釋:https://stackoverflow.com/a/14063373

  2. 正如@dfsq所說,page_id應該是pageId

這裏是與溶液的plunker:http://plnkr.co/edit/z843xZjIDQVe11edYLDR?p=preview

  • 您的自定義指令不應該是一個空元素。最好關閉像</post-listing>這樣的標籤以避免奇怪的行爲。在我的情況下,chrome將指令中的所有內容都包裝到div的末尾。這裏是一個使用transclude來顯示我的段落被包裹在自定義指令中的重複器:http://plnkr.co/edit/H3mDdi631flnC8AG2Q8i?p=preview
  • 相關問題