JavaScript指令不像我想象的那样工作

时间:2015-04-08 15:46:49

标签: javascript angularjs controller directive

Link to Plunker.

    (function(angular) {
      'use strict';
    angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
  }])
  .controller('testController', ['$scope', function($scope) {
    $scope.test.name = customerInfo.name;

  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        customerInfo: '=info'
      },
      templateUrl: 'my-customer-iso.html',
      controller: 'testController'
    };
  });
})(window.angular);

我有控制器A内部的值(在Plunker示例中,'控制器')我想通过使用指令传递给控制器​​B(在Plunker示例中,'testController')。标准的编程经验让我想到这样做,就像我在Plunker中尝试过的那样,但是当我看到Run结果时,我没有得到我想要的功能。

是什么给出了?

2 个答案:

答案 0 :(得分:1)

Link to plunker

您只会错过将$ scope添加到customerInfo

 $scope.test.name = $scope.customerInfo.name;

答案 1 :(得分:0)

scope标记直接注入对象,不需要单独的控制器,除非你需要在指令中有自定义逻辑。

如果它只是用于显示和结构,那么应该以正确的方向开始。



(function(angular) {
  'use strict';
angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        customerInfo: '=info'
      },
      template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}}'
    };
  });
})(window.angular);


Name: {{customerInfo.name}} Address: {{customerInfo.address}}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<body ng-app="docsIsolateScopeDirective">
  <div ng-controller="Controller">
  <my-customer info="naomi"></my-customer>
  <hr>
  <my-customer info="igor"></my-customer>
</div>
&#13;
&#13;
&#13;