我遇到了从控制器向指令注入/继承范围的问题。重要的是,模块没有分成它自己的var。
angular.module('articles').controller('ArticlesController', ['$scope, ...
]).directive('comments', ['$scope' ... //does not work!
答案 0 :(得分:4)
您不会将范围作为依赖项注入指令。应该是这样的:
.directive([function() {
return {
"link": function($scope, $element, $attrs) {
//code here
}
}
}]);
答案 1 :(得分:2)
最好的方法是将指令视为黑盒子。您为它提供了一些数据,并更新/显示它。您可以阅读有关指令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>
答案 2 :(得分:0)
我完全用其他几个范围绕过了$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>"
};
}
}
]);