【问题标题】:What is the difference in the scopes of a controller and a directive's controller?控制器和指令控制器的范围有什么区别?
【发布时间】:2016-04-28 05:19:35
【问题描述】:

控制器和指令控制器的作用域有什么区别?我很难理解其中的区别以及是否应该在 DDO 中为我的指令创建控制器。

下面我有一个定义为 MainCtrl 的控制器和一个子指令内的控制器。当我将 $scope 记录到控制台时,它们看起来一样吗?它们实际上是同一个对象吗?

var app = angular.module('plunker', [])

.controller('MainCtrl', function($scope) {
    $scope.first = 'first test'
    console.log($scope)
  })
  .directive('child', function() {
    return {
      //scope: {},
      template: '<div>{{second}}</div>',
      controller: function($scope) {            
        $scope.second = 'second test'
        console.log($scope)
      }
    }
  })

HTML

  <body ng-controller="MainCtrl">
    <child></child>
  </body>

【问题讨论】:

  • 简短的回答是肯定的,当不在指令中使用隔离范围时它们是相同的
  • 好的,所以如果使用隔离范围,那么指令的控制器将与其他控制器完全分离?
  • 我强烈建议您阅读this article
  • 是的....有点...指令控制器范围是一个新的范围,当它被隔离时没有继承
  • 那么在创建指令时,是用自己的控制器创建它们更好,还是使用父控制器?

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat


【解决方案1】:

阅读这篇文章。对你很有帮助。

http://www.angularjshub.com/examples/customdirectives/scope/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2015-04-30
    相关资源
    最近更新 更多