如何将此模块中的AngularJS控制器转换为其他格式?

时间:2014-03-17 14:04:39

标签: javascript angularjs angularjs-controller

我有这个AngularJS控制器;

angular.module('plunker', ['ui.bootstrap']);

var TabsDemoCtrl = function ($scope) {
  $scope.tabs = [
    { title:"Dynamic Title 1", content:"Dynamic content 1" },
    { title:"Dynamic Title 2", content:"Dynamic content 2", disabled: true }
  ];

  $scope.alertMe = function() {
    setTimeout(function() {
      alert("You've selected the alert tab!");
    });
  };

  $scope.navType = 'pills';
};

我想将它转换为另一个控制器(从AngularJS种子)到下面的格式;

angular.module('myApp.controllers', []).
  controller('MyCtrl1', [function() {

  }])
  .controller('MyCtrl2', [function() {

  }]);

index.html看起来像这样;

<div ng-controller="TabsDemoCtrl">
  <p>Select a tab by setting active binding to true:</p>
  <p>
    <button class="btn btn-default btn-sm" ng-click="tabs[0].active = true">Select second tab</button>
    <button class="btn btn-default btn-sm" ng-click="tabs[1].active = true">Select third tab</button>
  </p>
  <p>
    <button class="btn btn-default btn-sm" ng-click="tabs[1].disabled = ! tabs[1].disabled">Enable / Disable third tab</button>
  </p>
  <hr />

转换后的控制器应该如何?

我尝试了以下但是没有用。

angular.module('myApp.controllers', []).
  controller('TabsDemoCtrl', [function() {
    $scope.tabs = [
      { title:"Dynamic Title 1", content:"Dynamic content 1" },
      { title:"Dynamic Title 2", content:"Dynamic content 2", disabled: true }
    ];

    $scope.alertMe = function() {
      setTimeout(function() {
        alert("You've selected the alert tab!");
      });
    };

    $scope.navType = 'pills';    
    }])
  .controller('MyCtrl2', [function() {

  }]);

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您必须将$scope注入控制器才能使其正常工作

angular.module('myApp.controllers', []).
  controller('TabsDemoCtrl', ['$scope', function($scope) {
    $scope.tabs = [
      { title:"Dynamic Title 1", content:"Dynamic content 1" },
      { title:"Dynamic Title 2", content:"Dynamic content 2", disabled: true }
    ];

    $scope.alertMe = function() {
      setTimeout(function() {
        alert("You've selected the alert tab!");
      });
    };

    $scope.navType = 'pills';    
    }]);

答案 1 :(得分:0)

您可能希望在第二行指定$ scope。所以你的代码就像

angular.module('myApp.controllers', []).
controller('TabsDemoCtrl', ['$scope', function() {
    $scope.tabs = [
      { title:"Dynamic Title 1", content:"Dynamic content 1" },
      { title:"Dynamic Title 2", content:"Dynamic content 2", disabled: true }
    ];
....

另外,请确保您的myApp.controllers&#39;已经注册。这可能有所帮助。