0

我開始研究角度,似乎無法弄清楚爲什麼我的數據沒有傳遞給我的指令。我有代碼在這裏: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我獲取時獲得的價值數據不是。我似乎無法弄清楚,爲什麼它是這樣的。任何想法或建議都會有很大幫助。

+1

'頭像: 「=阿凡達」'但是你逝去'userAvatar' – taguenizy

回答

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> 
+0

你好,你試過嗎? – Sravan

1

我認爲你需要包裹name和字符串avatar,當你在HTML中使用它們。

<mj-directive name="name" userAvatar="userAvatar"></mj-directive>

而且該指令中,你應該有:

scope: { 
    user: "=name" 
    avatar: "=userAvatar" 
} 
相關問題