ng-init从另一个文件中获取值

时间:2016-03-03 19:17:41

标签: arrays angularjs ng-init

我正在使用angularJs,我必须使用多个值填充ng-init中的数组:

<div ng-init="script = [
            {tag:'tag1', title:'Title1 here', plot:'here goes the plot1'},
            {tag:'tag2', title:'Title2 here', plot:'here goes the plot2'},
            {tag:'tag3', title:'Title3 here', plot:'here goes the plot3'}
            ]">
</div>

正如您可能想象的那样,“情节”字段是一个字符串,如果我在那里写它可能会很大并且令人困惑。是否可以从另一个文件中获取它? 例如,我可以创建三个名为plot1,plot2,plot3的文件,我可以将它们调用到我的HTML文件中

2 个答案:

答案 0 :(得分:1)

我不建议使用ng-init。我建议使用视图控制器并通过以下逻辑加载脚本。

.controller( 'viewController', function($scope, $http){
     $http.get(<location of file to load>)
     .then( function(rsp){
          $scope.script = rsp
     })
})

如果你想加载多个文件,那么要么多个请求,,如果它们相互依赖,请使用$q.all确保全部加载:

$q.all([
    $http.get(<location of file1 to load>),
    $http.get(<location of file2 to load>),
    $http.get(<location of file3 to load>)
])
.then( function( rsps ){
     $scope.script = rsps
})

链接:

答案 1 :(得分:0)

.controller( 'viewController', function($scope, $http){
     $http.get(url)
     .then( function(response){
          $scope.initVal = response;
     })
})

<div ng-init="initVal ">
</div>