$scope不会使用点表示法从控制器注入/继承到指令

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

本文关键字:注入 控制器 继承 指令 表示 scope      更新时间:2023-09-26

我在将范围从控制器注入/继承到指令时遇到问题。重要的是,模块没有被分离成自己的变量。

angular.module('articles').controller('ArticlesController', ['$scope, ...
]).directive('comments', ['$scope' ... //does not work!

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

.directive([function() {
    return {
        "link": function($scope, $element, $attrs) { 
             //code 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>"
       };
      }
     }
    ]);