无法在HTML中打印的函数中的作用域-AngularJS

时间:2018-11-01 15:27:02

标签: javascript html angularjs axios

我正在执行API调用,并使用从API调用获得的值更新数组。如果数组在函数之外,我可以用HTML打印数组,但是API调用中的值不在数组中。但是,如果我将数组移动到函数内部,则会得到所需的结果,但是html不会将其打印出来。

我为同一东西创建了两个小提琴,一个在函数外部,另一个在函数内部。

外部功能:

'use strict';

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

app.controller('MainCtrl', ['$scope', function($scope) {

  $scope.getTitle = function() {
    axios.get('https://jsonplaceholder.typicode.com/todos/1')
      .then(function(res) {
        $scope.title = res.data.title;
        console.log($scope.title)
      });
    return $scope.title;
  };

  $scope.links = [{
      title: 'Designer',
      url: '/designer',
    },
    {
      title: 'Modeler',
      url: '/modeler',
    },
    {
      title: 'Recommender',
      url: $scope.getTitle(),
    }
  ];
  console.log($scope.links)
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div id="mainContainer" ng-app="angularTest" ng-controller="MainCtrl">
  <ul ng-repeat="link in links track by $index">
    <a href="{{link.url}}">
      <li>{{link.title}}</li>
    </a>
  </ul>
</div>

内部功能:

'use strict';

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

app.controller('MainCtrl', ['$scope', function($scope) {

  $scope.getTitle = function() {
    axios.get('https://jsonplaceholder.typicode.com/todos/1')
      .then(function(res) {
        $scope.title = res.data.title;

        $scope.links = [{
            title: 'Designer',
            url: '/designer',
          },
          {
            title: 'Modeler',
            url: '/modeler',
          },
          {
            title: 'Recommender',
            url: $scope.title,
          }
        ];
        console.log($scope.links)
      });
  };
  
  $scope.getTitle();
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div id="mainContainer" ng-app="angularTest" ng-controller="MainCtrl">
  <ul ng-repeat="link in links track by $index">
    <a href="{{link.url}}">
      <li>{{link.title}}</li>
    </a>
  </ul>
</div>

请咨询。

0 个答案:

没有答案