【问题标题】:AngularJs use constant in other constantAngularJs 在其他常量中使用常量
【发布时间】:2015-06-15 18:56:27
【问题描述】:

如果我这样声明 1 个常量:

app.constant('appHelper', {
    first: 'Firstname',
    last: 'Lastname'
});

然后尝试在第二个常量中使用它,如下所示:

app.constant('appHelper2', {
    fullName: appHelper.first + '' + appHelper.last
});

不起作用。 Error: appHelper is undefined.

任何想法我该怎么做?

【问题讨论】:

标签: angularjs


【解决方案1】:

当然:

var appHelper = {
    first: 'Firstname',
    last: 'Lastname'
}

app.constant('appHelper', appHelper);
app.constant('appHelper2', {
    fullName: appHelper.first + '' + appHelper.last
});

【讨论】:

    【解决方案2】:

    参考和致谢:

    is there a way in Angularjs to define constants with other constants?

    http://michalostruszka.pl/blog/2012/12/23/angular-better-constant-values/

    基于此,以下可能适合你。

    var myApp = angular.module("exampleApp",[]);
    
    myApp.constant('HELPER', (function() {
      // Define your variable
      var appHelper = {
        first: 'Firstname',
        last: 'Lastname'
    };
      // Use the variable in your constants
      return {
        appHelper:appHelper,
        fullName: appHelper.first + '' + appHelper.last
      }
    })());
    
    myApp.controller("ExampleCtrl", function(HELPER){
      $scope.firstname = HELPER.appHelper.firstname;
      $scope.fullName = HELPER.fullName;
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2013-08-31
      • 2012-04-20
      • 2021-12-17
      • 1970-01-01
      • 2021-07-29
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多