Ui-Router在视图中创建新的控制器

时间:2016-06-15 14:46:34

标签: angularjs angular-ui-router

鉴于我将进入以下状态:

  $stateProvider.state('applicant', {
  url: "/admin/applicants/:name",
  templateProvider: function($http, $stateParams) {
  return $http({
    method: 'GET',
    url: 'http://example.com/applicant',
    params: {
      request: $stateParams.name,
    }
  }).then(function successCallback(html) {
    return html.data;
  });
},
  controller: 'SendToCtrl'
});

$http返回的视图如下所示:

<script>
app.controller('ChildController', ['$scope', function($scope) {
$scope.applicant = <?php echo $applicant ?>;
}]);
</script>
    <div class="row" ng-controller="ChildController">
<div class="col-md-12">
{{applicant.State}}
</div>
</div>

我得到参数'ChildController'不是函数错误。我读到,在常规ng-view调用时,不支持这样的新控制器,但无法找到ui-router的答案。如果我需要模板来显示仅在提供视图时才显示的数据,那么进行模板化的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

所以我无法在视图中生成控制器,就像我想要的那样,所以我使用状态生成的控制器并将php变量附加到视图中,然后从所述集合控制器中再次拾取它,像这样:

州定义:

$stateProvider.state('applicant', {
      url: "/admin/applicants/:name",
      templateProvider: function($http, $stateParams) {
      return $http({
        method: 'GET',
        url: 'http://example.com/applicant',
        params: {
          request: $stateParams.name,
        }
      }).then(function successCallback(html) {
        return html.data;
      });
    },
      controller: 'SendToCtrl'
    });

查看:

<?php
$applicant = str_replace('"', "'", $applicant);
?>
<div class="row">
<div id="fetchMe" class="col-md-12">
</div>
</div>
<script>
applicant = <?php echo $applicant ?>;
$('#fetchMe').data('key',applicant);
</script>

SendToCtrl:

app.controller('SendToCtrl', ["$scope", "$stateParams", "$state", function($scope, $stateParams, $state) {

    console.log($stateParams);
    $scope.applicant = $("#fetchMe").data('key');
    console.log($scope.applicant);
}]);

:)