自定义Angular指令链接函数中的属性始终为null

时间:2015-12-02 18:44:24

标签: javascript angularjs angularjs-directive

Plunkr here

我有一个自定义指令,用于显示基本用户数据。 HTML模板能够使用{{xxx}}语法呈现用户数据,但我还需要使用用户数据对象中的一个属性来检索用户的照片。

我的问题是在链接函数中,personData值始终为null。我在人身上添加了$ observe,但它也总是为空。

是否有办法观察对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',

  };

}]);

1 个答案:

答案 0 :(得分:0)

我假设您的意图是监视对personData对象所做的更改,而不是监视指令中DOM属性person的实际值。这是对的吗?

我会在这里使用$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": "KatieJ@demo.com",
      "mobilePhone": null,
      "officeLocation": "12/1110",
      "preferredLanguage": "en-US",
      "surname": "Jordan",
      "userPrincipalName": "KatieJ@demo.com",
      "id": "a0da13e4-1866-492e-96e6-8a2a4b60f650"
   },
   {
      "displayName": "James Jordan",
      "givenName": "James",
      "jobTitle": "Auditor",
      "mail": "JamesJ@demo.com",
      "mobilePhone": null,
      "officeLocation": "12/1110",
      "preferredLanguage": "en-US",
      "surname": "Jordan",
      "userPrincipalName": "JamesJ@demo.com",
      "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',

  };

}]);