问题描述:

I'm using angular declarations without using or injecting $scope var, but with this. declarations

 var app = angular.module('myApp', []);

app.controller('myCtrl', myCtrlFunction);

function myCtrlFunction() {

this.myUrl = "This is myUrl content";

}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl as vm">

<p>Here I put my var myUrl:</p>

<h3>{{vm.myUrl}}</h3>

</div>

网友答案:

Yes, because it has dependency injection. In your current setup, your controller requires $location to be a global variable. Also, you need to supply a an array with string values for the parameter names, so angular still knows what to inject after the parameters are changed by minification algorithms.

So, use either one of those setups:

var app = angular.module('myApp', []);

app.controller('myCtrl', ['$location', myCtrlFunction]); 

function myCtrlFunction($location) {
    this.myUrl = "This is myUrl content";
}

or:

var app = angular.module('myApp', []);
app.controller('myCtrl', myCtrlFunction); 

function myCtrlFunction($location) {
    this.myUrl = "This is myUrl content";
}
// tell angular what parameters are expected
myCtrlFunction.$inject = ['$location'];

More about dependency injection in Angular.

网友答案:

You need to inject $location.

 var app = angular.module('myApp', []);
     app.controller('myCtrl', myCtrlFunction); 

     function myCtrlFunction(**$location**) {
        this.myUrl = $location.absUrl();
     }

You got away with the previous version because you weren't actually using the $scope keyword. But with $location you are specifically using it, so you need to inject it.

相关阅读:
Top