从控制器调用全局变量到HTML查看AngularJS

时间:2015-02-13 05:14:45

标签: javascript jquery angularjs angularjs-directive angularjs-scope

我在Plunkr中有以下代码。 http://plnkr.co/edit/8sBafktFzFa8fCLLJgMF

这是我的js文件

angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {



  $scope.open = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalDemoCtrl',
      size: size
    });

    var applicantID = 12;
  };


  $scope.submit_info = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent1.html',
      controller: 'ModalDemoCtrl',
      size: size
    });
  };
});

这是我的html页面

<!doctype html>
<html ng-app="ui.bootstrap.demo">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

<div ng-controller="ModalDemoCtrl">
    <script type="text/ng-template" id="myModalContent.html">

            <h3>I'm a modal!</h3>

            <button class="btn btn-default"  ng-click="submit_info('lg')">Submit</button>

    </script>
    <script type="text/ng-template" id="myModalContent1.html">

            <h3>CaseID: </h3>
            {{ applicantID }}

    </script>

    <button class="btn btn-default" ng-click="open()">Set caseID</button>

</div>
  </body>
</html>

我希望能够在点击“setID”按钮时分配applicantID,点击“提交”按钮后,它会显示传递的申请人ID值“12”。但它不断传递空数据。

3 个答案:

答案 0 :(得分:0)

您可以使用$ rootScope绑定它: -

$rootScope.applicantID = 12;

Plunker

答案 1 :(得分:0)

您必须将applicantID变量与范围相关联。只有这样你才能在视图中访问它。

    angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

      $scope.applicantID = 12;
      .
      .

    });

更新了Plunker here

答案 2 :(得分:0)

如果我以正确的方式理解你的问题,这就是答案。

angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {



  $scope.open = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalPopupCtrl,
      size: size
    });

    var applicantID = 12;
  };






});

  function ModalPopupCtrl($scope,$modal){

  $scope.applicantID = 12;

  $scope.submit_info = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent1.html',
      controller: ModalPopupCtrl,
      size: size
    });
  };
}