2017-07-28 59 views
2

我有一個指令「頭像」,它採取一個「用戶」的對象,並顯示用戶的圖像。AngularJS 1.6:Directive模板內指令模板只工作第一次

這工作正常。

現在我有另一個指令'用戶',它顯示給定'用戶'對象的名稱,幷包括使用其模板的指令。

這是有效的。第一次。

當我更新'用戶'對象時,只有名稱改變,圖像(頭像)不會改變。

我的問題:我如何使它工作?

頭像指令:

(鏈接函數:如果用戶對象並有一個「分機」屬性,它計算圖像路徑(「SRC」),否則它會顯示一個標準template.jpeg)

directive('avatarSmall', function() { 

    return { 
    restrict: "E", 
    replace: true, 
    templateUrl: "scripts/directives/avatar/small.html", 
    link: function(scope, element, attrs) { 
     var r = "images/avatars/"; 
     var ext = scope.user.ext; 
     r += ext != undefined && ext.length >= 3 ? scope.user.ID + "." + ext : "template.jpeg"; 
     scope.src = r; 
    }, 
    scope: { 
     user: '=' 
    } 
    } 
}) 

頭像模板:

<div class="circle-wrapper-small"> 
    <img class="circle-img-small" 
     ng-src="{{src}}"> 
</div> 

用戶指令:

directive('user', function($compile) { 
    return { 
    restrict: "E", 
    replace: true, 
    templateUrl: "scripts/directives/user/template.html", 
    scope: { 
     user: '=' 
    } 
    } 
}) 

用戶模板:

<div> 
    <div class="media-left"> 
    <avatar-small user="user" /> 
    </div> 
    <div class="media-body"> 
    <h4 class="media-heading">{{user.name}} {{user.surname}}</h4> 
    </h5> 
    </div> 
</div> 

回答

2

因爲你的頭像指令的代碼執行唯一的,在指令初始化。如果您想更新更改,則應該向您的指令提供$broadcast事件,並在$broadcast事件中執行該代碼。

欲瞭解更多信息有關$emit$broadcast$on事件中,你可以瀏覽這個帖子:Usage of $broadcast(), $emit() And $on() in AngularJS

事情是這樣的:

父控制器

$scope.user = { 
    // object properties 
} 

// watch "$scope.user" for changes 
$scope.$watch('user', function(newVal, oldVal){ 
    if(newVal !== oldVal) { 
     // send new "$scope.user" to your directive 
     $scope.$broadcast('userObjChanged', $scope.user); 
    } 
}, true); 

和你的指令內

// catch event from parent's controller with new user object 
$scope.$on('userObjChanged', function(event, data) { 
    console.log(data); // here is the new user object from parent's scope 
}) 
+1

感謝您的好評,今天我學到了一些新東西!此外(對於其他用戶也有同樣問題),我用ng-include ='avatar-template-source-source'替換'',但結果是一樣的,它只在第一次運行。 – MehmetGunacti

+0

我很高興你覺得它有幫助。乾杯! –