Javascript 自定义角度指令链接函数中的属性始终为空
我有一个自定义指令,我正在构建它来显示基本的用户数据。HTML模板能够使用{xxx}语法呈现用户数据,但是我还需要使用用户数据对象中的一个属性来检索用户的照片 我的问题是,在link函数中,personData值始终为null。我在person上添加了$observe,但它也总是空的 是否有方法观察personData对象的更改并对更改执行操作 指令代码:Javascript 自定义角度指令链接函数中的属性始终为空,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有一个自定义指令,我正在构建它来显示基本的用户数据。HTML模板能够使用{xxx}语法呈现用户数据,但是我还需要使用用户数据对象中的一个属性来检索用户的照片 我的问题是,在link函数中,personData值始终为null。我在person上添加了$observe,但它也总是空的 是否有方法观察personData对象的更改并对更改执行操作 指令代码: app.directive('graphPerson', ['$http', function() { return { res
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',
};
}]);
我假设您的目的是监视对
personData
对象所做的更改,而不是监视指令中DOM属性person
的实际值。对吗
我会在这里使用$scope.$watch()
见:
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',
};
}]);