javascript - Controller 数据未传递给指令

标签 javascript angularjs angularjs-directive angularjs-scope angularjs-controller

我开始研究 Angular ,似乎无法弄清楚为什么我的数据没有传递给我的指令。我这里有代码:https://plnkr.co/edit/ONwYevQ4NbvBVjTwARHl?p=preview

我的代码: 应用程序.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>

模板.html:

<div class='line'>
  <p>Name : <strong>{{name}}</strong></p>
  <img class="avatar" src={{avatar}}/>
</div>

name 值已传递,但我在获取数据时获取的 avatar 值未传递。我似乎无法弄清楚为什么会这样。任何想法或建议都会有很大帮助。

最佳答案

我认为您在绑定(bind) avatar 后使用了错误的名称 userAvatar 而不是 avatar

您的绑定(bind),

  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>

关于javascript - Controller 数据未传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39617665/

相关文章:

javascript - Thinky.io hasMany 不保存新模型实例

javascript - jQuery - 为元素分配 ID

javascript - angularJS 服务 - 返回检索数据和管理数据对象的 promise ?

javascript - 特定标签名称的 AngularJS 指令

javascript - 为什么 $watch 中的监听函数没有被触发?

javascript - 如何使网站始终以纵向显示?

Javascript:如何将找到的 string.replace 值传递给函数?

javascript - 当 AngularJS 返回 $http 结果时如何隐藏或显示菜单项

javascript - 当 DOM 中的元素太多时,Angular ng 类性能问题

angularjs - Angular 中为自定义指令保留的命名空间?