控制器数据未传递给指令

Controller data not passed to directive

我开始调查 angular,但似乎无法弄清楚为什么我的数据没有传递到我的指令。我这里有代码: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 值未传递。我似乎无法弄清楚,为什么会这样。任何想法或建议都会有很大帮助。

我认为你取错了名字 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>

我认为在 HTML.

中使用 nameavatar 时需要用字符串包裹它们

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

在指令中你还应该有:

scope: {
    user: "=name"
    avatar: "=userAvatar"
}