![](/img/trans.png)
[英]Typescript Angularjs Controller Scope undefined when calling from Directive
[英]AngularJS $scope Undefined When Compiling Controller In Directive
我正在使用ant来构建/ uglyfy我的AngularJS,并且每当我在指令中有一个控制器时,都会收到未定义的$ scope错误。 代码示例是这样的:
app.directive('directive1',['$compile', '$http',function($compile, $http) {
return {
restrict: "A",
controller : function($scope) {
var posts = {};
this.addPosts = function($scope, newPosts) {
angular.extend(posts, newPosts);
//$scope.$apply(function() {
$scope.posts = posts;
//});
};
},
link: function (scope, element, attrs) {
scope.posts = {};
}
};
}]);
我的问题是,如何定义控制器的$ scope使其在编译时不会出现未定义状态?
您希望将对指令定义执行的相同的minifier / ulgifier安全方法应用于控制器。
因此,您的控制器来自:
controller : function($scope) {
至:
controller: ['$scope',function($scope) {
uglifier正在将$scope
重命名$scope
类似'e'之类的短字符,这对于大小来说非常有用,但是Angular不知道要向'e'中注入什么。
uglifier不会更改字符串。 因此,上面的新代码让angular知道应该将$ scope注入到'e'中(或uglifier给它起的任何名字)。
this.addPosts = function($scope, newPosts) {
什么叫这个功能? 为什么要尝试将$ scope传递给它? 我认为您应该将其更改为:
$scope.addPosts = function(newPosts) {
因为您想获得第一个$ scope ...而不是试图传递给addPosts的任何范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.