$scope 不是 injected/inherited 从控制器到带点符号的指令

$scope not being injected/inherited from controller to directive with dot notation

我对 injecting/inheriting 从控制器到指令的作用域有疑问。重要的是,模块没有分离到它自己的 var.

angular.module('articles').controller('ArticlesController', ['$scope, ...

]).directive('comments', ['$scope' ... //does not work!

您没有将作用域作为依赖项注入到指令中。应该是这样的:

.directive([function() {
    return {
        "link": function($scope, $element, $attrs) { 
             //code here
        }
    }
}]);

最好的方法是将指令视为黑盒。你向它提供一些数据,然后它 updates/displays 它。您可以阅读有关指令 here 的所有必需信息,并像这样声明指令的输入和输出:

.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      myParameter: '=' //this declares directive's interface (2 way binded)
    },
    link: function (scope, element) {
      console.log(scope.myParameter);
    }
  };
});

然后您可以将此指令用作:

<my-directive my-parameter='variable_declared_in_controller'></my-directive>

我刚刚用几个其他范围完全绕过了 $scope

    .directive('comments', ['$stateParams', '$location', 'Articles',
  function ( $stateParams, $location, Articles) {

   if ($stateParams.articleId != null){

   var article = Articles.get({
        articleId: $stateParams.articleId
      });

   var comments = {articleId: article.articleId, created: Date.now, comment:"Hello, World!", user: "admin" };

       return{
        restrict: "A",
        scope: true,
        template: "<div></div>"
       };
      }
     }
    ]);