2016-09-22 68 views
1

我試圖取決於一個範圍變量的DOM元素將改變類型實現..根據AngularJS變量改變DOM元素類型

所以說我有一個像範圍VAR:

$scope.post = { 
    title:   'Post title goes here!', 
    slug:   'post-title-goes-here', 
    category:  'News', 
    featured_image: '//src.jpg' 
}; 

和DOM元素,如:

<a href="#/post/{{post.slug}}"> 
    <div style="background-image: url({{post.featured_image}});"> 
     <small ng-if="post.category">{{post.category}}</small> 
     <h3>{{post.title}}</h3> 
    </div> 
</a> 

但是,如果VAR $scope.post.slug是空的DOM元素看起來像:

<div> 
    <div style="background-image: url({{post.featured_image}});"> 
     <small ng-if="post.category">{{post.category}}</small> 
     <h3>{{post.title}}</h3> 
    </div> 
</div> 

很明顯,我可以做一個ng-if並複製每一點代碼,但我試圖避免這一點!

像這樣的理想:

<{{post.slug ? 'a href="#/post/'+post.slug+'"' : 'div'}}> 
    <div style="background-image: url({{post.featured_image}});"> 
     <small ng-if="post.category">{{post.category}}</small> 
     <h3>{{post.title}}</h3> 
    </div> 
</{{post.slug ? 'a' : 'div'}}> 

回答

0

我不認爲你可以直接與角度實現這一目標。 HTML需要在角度注入之前定義。但是對於這種情況,我認爲使用控制器邏輯中的函數控制錨點更好。只需使用div和ng-click ='yourFunction()'設置您的DOM,並在存在post.slug的情況下,使用角度路由系統進行導航。

0

自定義指令將允許您執行ng-if來確定<a>標記或<div>標記而不污染您的視圖。指令中的ngTransclude包含您的內容。

查看:

<div ng-repeat="post in posts"> 
    <div slug-link="post.slug"> 
     <div style="background-image: url({{post.featured_image}});"> 
      <small ng-if="post.category">{{post.category}}</small> 
      <h3>{{post.title}}</h3> 
     </div> 
    </div> 
</div> 

指令:

.directive('slugLink', function() 
{ 
    return { 
    transclude: true, 
    scope: { 
     slug: '=slugLink' 
    }, 
    template: '<a ng-href="{{slug}}" ng-if="slug" ng-transclude></a><div ng-if="slug == \'\'" ng-transclude></div>' 
    }; 
}); 

查看完整的源在Plunkr

+0

的條件是兩個'NG-if's相同... –

+0

你」再右吧。修正並更新了這一點。我正在用幾種不同的方式來做這個檢查。 OP可以編輯這些值以匹配他擁有的數據。 – AndrewR