如何在我的控制器中使用常量URL

时间:2018-04-15 17:11:31

标签: angularjs

这里我在.constant中定义了一些网址,如

app.constant('UrlConstant',function(){
    var GlobalUrl = "http://localhost:5833/";}) 

这个UrlConstant如何在我的控制器中使用

var app = angular.module('MyApp', [])
app.controller('twoWayBinding', function ($scope, UrlConstant) {
    $scope.changefun = function () {
        console.log(UrlConstant.GlobalUrl);
    }

console.log我得到了不明白的

2 个答案:

答案 0 :(得分:2)

您需要将常量声明为

app.constant('UrlConstant','http://localhost:5833/')

<强>样本

&#13;
&#13;
var app = angular.module('MyApp', [])
app.controller('twoWayBinding', function ($scope, UrlConstant) {
    $scope.changefun = function () {
        console.log(UrlConstant);
   }
});
    
app.constant('UrlConstant','http://localhost:5833/')
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="MyApp" ng-controller="twoWayBinding">
  <button ng-click="changefun()">GetVal</button>
   
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用object作为常量值:

app.constant('UrlConstant', {
    GlobalUrl: "http://localhost:5833/"
});

然后您可以使用UrlConstant.GlobalUrl

来调用它
var app = angular.module('MyApp', [])
app.controller('twoWayBinding', function ($scope, UrlConstant) {
    $scope.changefun = function () {
        console.log(UrlConstant.GlobalUrl);
    }
})
相关问题