Rakesh Rai
Rakesh Rai

Reputation: 1

Load angularJs controller

I had already declared my app and controller in separate file and below is how i am loading my controller html DOM but it is not showing that message. Can someone please guide how to achieve this.

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);

Please let me know how to inject or load ng-controller html dynamically.

Upvotes: 0

Views: 131

Answers (4)

Rakesh Rai
Rakesh Rai

Reputation: 1

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>

Upvotes: 0

Raj
Raj

Reputation: 149

You can try Like below Example:-

Html Page:

<!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 Page:

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

Upvotes: 0

Paul Boutes
Paul Boutes

Reputation: 3315

A proper way is to declare your Controller into an anonymous function, and add it to a module. Then, you have to set your ngApp.

Controller.js

Here, we will declare our controller, and create an app module. Then, we will declare ctrl as our controller into our app module.

  (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>

And don't forget to include your script tag :

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

Upvotes: 0

Chetan Purohit
Chetan Purohit

Reputation: 392

Your controller declaration is wrong. You should do it like this:

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

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

Upvotes: 1

Related Questions