AngularJS自定义指令 - 隔离范围问题

时间:2017-09-11 15:55:30

标签: angularjs

我正在试图弄清楚为什么以下内容无法正常工作。我以为它会显示: 用户:Jakob Jenkov用户:John Doe

然而,它显示了这个:

用户:用户:

HTML:    

<html ng-app="plunker">
<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>
<body ng-controller="MyController as $ctrl">
    <userinfo user="jakob"></userinfo>
    <userinfo user="john"></userinfo>
  </body>
</html>

JAVASCRIPT:

var myapp = angular.module('plunker', []);
myapp.directive('userinfo', function() {
    var directive = {};

    directive.restrict = 'E';

    directive.template = "User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>";

    directive.scope = {
        user : "="
    }

    return directive;
});
myapp.controller("MyController", function() {
    var $ctrl = this;
    $ctrl.jakob = {};
    $ctrl.jakob.firstName = "Jakob";
    $ctrl.jakob.lastName  = "Jenkov";

    $ctrl.john = {};
    $ctrl.john.firstName = "John";
    $ctrl.john.lastName  = "Doe";
}); 

2 个答案:

答案 0 :(得分:1)

您正在使用Controller As语法,因此您需要将控制器别名$ctrl添加到传递给指令的变量中:

<body ng-controller="MyController as $ctrl">
  <userinfo user="$ctrl.jakob"></userinfo>
  <userinfo user="$ctrl.john"></userinfo>
</body>

如果没有$ctrl,angular将直接在$scope上查找未设置的变量,因此将undefined传递给您的指令而不是所需的用户对象。

答案 1 :(得分:0)

一种方法是这样的:

<html ng-app="plunker">
<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script>
    var myapp = angular.module('plunker', []);

    myapp.directive('userinfo', function() {

      var directive = {};

      directive.restrict = 'E';

      directive.template = "User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>";

      directive.scope = {
        user : "="
      }

      return directive;
    });

    myapp.controller("MyController", function() {

      this.jakob = {
        firstName: "Jakob",
        lastName: "Jenkov"
      }
      this.john = {
        firstName: "John",
        lastName: "Doe"
      }

    }); 

  </script>
</head>
<body ng-controller="MyController as myCtrl">
  <userinfo user="myCtrl.jakob"></userinfo>
  <userinfo user="myCtrl.john"></userinfo>
</body>
</html>