我正在使用 ant 来构建/丑化我的 AngularJS,每次我在指令中有一个 Controller 时,我都会收到一个未定义的 $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 = {};
}
};
}]);
我的问题是,如何定义 Controller 的 $scope ,使其在编译时不会显示为未定义?
最佳答案
您希望将与指令定义相同的 minifier/ulgifier 安全方法应用到 Controller 。
所以你的 Controller 来自:
controller : function($scope) {
至:
controller: ['$scope',function($scope) {
uglifier 正在将 $scope
重命名为诸如“e”之类的简短名称,这对于大小来说非常合适,但 Angular 不知道要向“e”中注入(inject)什么内容。
丑化器不会改变字符串。因此,上面的新代码让 Angular 知道它应该将 $scope 注入(inject)“e”(或者 uglifier 给它的任何名称)。
关于javascript - 在指令中编译 Controller 时,AngularJS $scope 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229337/