我开始研究角度,似乎无法弄清楚为什么我的数据没有传递给我的指令。我的代码在这里:https://plnkr.co/edit/ONwYevQ4NbvBVjTwARHl?p=preview
我的代码: app.js:
var app = angular.module('mjApp', []);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.name = "m.jacionis";
$scope.avatar = null;
$scope.fetchData = function(){
var callUrl = 'https://api.github.com/search/users?q=' + $scope.name;
$scope.avatar = "http://images.clipartpanda.com/sad-face-clipart-black-and-white-9c4eqRyyi.png";
$http({
method: 'GET',
url: callUrl
}).then(function successCallback(response) {
$scope.avatar = response.data.items.length > 0 ?
response.data.items[0].avatar_url : $scope.avatar;
console.log($scope.avatar);
}, function errorCallback(response) {
console.log('avatar stays the same');
});
};
}]);
app.directive("mjDirective", function(){
return {
restrict: "EA",
templateUrl: 'template.html',
scope: {
name: "=name",
avatar: "=avatar"
}
};
});
的index.html:
<!DOCTYPE html>
<html ng-app="mjApp">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="parent" ng-controller="MainController">
<div class="line">
<input type='text' ng-model='name' />
<input type="button" ng-click="fetchData()" value="Submit User Name" />
</div>
<mj-directive name=name userAvatar=userAvatar></mj-directive>
</div>
</body>
</html>
template.html:
<div class='line'>
<p>Name : <strong>{{name}}</strong></p>
<img class="avatar" src={{avatar}}/>
</div>
name
值已传递,但我获取数据时获得的avatar
值不是。{我似乎无法弄明白,为什么会这样。任何想法或建议都会有所帮助。
答案 0 :(得分:1)
我认为您绑定了userAvatar
avatar
而不是avatar
你的绑定,
scope: {
name: "=name",
avatar: "=avatar"
}
所以,你必须在指令中使用名字和头像。
<body>
<div class="parent" ng-controller="MainController">
<div class="line">
<input type='text' ng-model='name' />
<input type="button" ng-click="fetchData()" value="Submit User Name" />
</div>
<mj-directive name=name avatar=avatar></mj-directive>
</div>
</body>
更改指令,
<mj-directive name=name avatar=avatar></mj-directive>
答案 1 :(得分:1)
我认为在HTML中使用时,我需要将name
和avatar
包装在字符串中。
<mj-directive name="name" userAvatar="userAvatar"></mj-directive>
同样在指令内你应该:
scope: {
user: "=name"
avatar: "=userAvatar"
}