2015-12-02 36 views
0

Plunkr here屬性自定義角向鏈路功能總是空

我有一個自定義指令,我的構建,以顯示基本用戶數據。 HTML模板能夠使用{{xxx}}語法呈現用戶數據,但我還需要使用用戶數據對象中的某個屬性來檢索用戶的照片。

我的問題是,在鏈接函數中,personData值始終爲空。我添加了一個$觀察對象,但它也一直爲空。

有沒有辦法觀察personData對象的更改並對更改執行操作?

指令代碼:

app.directive('graphPerson', ['$http', function() { 
    return { 
    restrict: 'E', 
    scope: { 
     personData: '=person' 
    }, 
    link: function($scope, element, attrs, ctrl) { 
     console.log("Directive was linked"); 
     console.log($scope.personData); 
     attrs.$observe('person', function(newValue, oldValue) { 
     console.log($scope.personData); 
     if ($scope.personData) { 
      //hard-coded photo for demo purposes 
      $scope.myPhoto = "http://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Blank_woman_placeholder.svg/315px-Blank_woman_placeholder.svg.png"; 
     } 
     }); 
    }, 
    templateUrl: 'graph-person.html', 

    }; 

}]); 

回答

0

我假設你的目的是監測您的指令屬性personpersonData對象進行,而不是對DOM的實際值的變化。那是對的嗎?

我會在這裏使用$scope.$watch()

請參見:http://plnkr.co/edit/SU5x1F5tZKQWk4VK5OGO

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
    $scope.personData = null; 
    $scope.people = [ 
    { 
     "displayName": "Katie Jordan", 
     "givenName": "Katie", 
     "jobTitle": "Auditor", 
     "mail": "[email protected]", 
     "mobilePhone": null, 
     "officeLocation": "12/1110", 
     "preferredLanguage": "en-US", 
     "surname": "Jordan", 
     "userPrincipalName": "[email protected]", 
     "id": "a0da13e4-1866-492e-96e6-8a2a4b60f650" 
    }, 
    { 
     "displayName": "James Jordan", 
     "givenName": "James", 
     "jobTitle": "Auditor", 
     "mail": "[email protected]", 
     "mobilePhone": null, 
     "officeLocation": "12/1110", 
     "preferredLanguage": "en-US", 
     "surname": "Jordan", 
     "userPrincipalName": "[email protected]", 
     "id": "b0da13e4-1866-492e-96e6-8a2a4b60f651" 
    } 
    ]; 
    $scope.clickMe = function(index) { 
    $scope.personData = $scope.people[index]; 
    } 

}); 
app.directive('graphPerson', ['$http', function() { 
    function getImageUrl(id) 
    { 
    console.log("I should get the URL For: " + id); 
    return id; 
    } 
    return { 
    restrict: 'E', 
    scope: { 
     personData: '=person' 
    }, 
    link: function($scope, element, attrs, ctrl) { 
     console.log("Directive was linked"); 

     $scope.$watch('personData', function(newValue) { 
     console.log($scope.personData); 
     if ($scope.personData) { 
      $scope.myPhoto = getImageUrl($scope.personData.id); 
     } 
     }); 
    }, 
    templateUrl: 'graph-person.html', 

    }; 

}]); 
+0

完美!謝謝! –