加载angularJs控制器

时间:2015-08-24 11:42:03

标签: javascript jquery angularjs

我已经在单独的文件中声明了我的应用程序和控制器,下面是我如何加载我的控制器html DOM,但它没有显示该消息。有人可以指导如何实现这一目标。

HTML:

<div id="bnProblemList">
    <div ng-controller="problemListCtrl" data-ng-init="init()">
        <div ng-view="">this is my message = {{message}}</div>
    </div>
</div>

JS:

html = $j('#bnProblemList').html();
$compile(html)(scope);

请让我知道如何动态注入或加载ng-controller html。

4 个答案:

答案 0 :(得分:1)

您的控制器声明错误。你应该这样做:

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

myApp.controller('problemListCtrl', ['$scope', 
  function($scope) {
      $scope.message = "This is my message :-)";
  }
]);

答案 1 :(得分:0)

正确的方法是将控制器声明为匿名函数,并将其添加到模块。然后,您必须设置ngApp

<强> Controller.js

在这里,我们将声明我们的控制器,并创建一个 app 模块。然后,我们将ctrl声明为我们的app模块中的控制器。

  (function(){

  function Controller($scope) {

    $scope.name = 'toto';

  }

  angular
  .module('app', [])
  .controller('ctrl', Controller);

  })();

<强> HTML

  <body ng-app='app' ng-controller="ctrl">

    <p>My name is {{name}}</p>

 </body>

并且不要忘记包含脚本标记

<script src="controller.js"></script>

答案 2 :(得分:0)

您可以尝试以下示例: -

Html页面:

<!DOCTYPE html>
<html ng-app="MyApp">
<head>
 <title> Controller</title>  
 <script src="../Js/angular.min.js"></script>
 <script src="../Js/Controller.js"></script>   
</head>
<body>
  <div ng-controller="MyFirstController">
    {{ Msg }}
  </div>
</body>
</html>

ControllerJs页面:

var MyApp=angular.module("MyApp",[]);
MyApp.controller("MyFirstController",function($scope){
  $scope.Msg="Hello First Conroller";
})

答案 3 :(得分:0)

i was able to load/ inject controller dynamically by the help of below code

<div id="bn" ng-controller="myCtrl as vm">
    <div ui-view=''></div>
</div>

<script>
    angular.element(document).injector().invoke(function($compile, $state) {
        $state.go('myCtrl');
        var scope = angular.element($j("#bn")).scope();
        $compile($j("#bn"))(scope);
    });
</script>