angularjsrazorng-controller

How does ng-controller locate the right controller file?


I'm brand new to AngularJS. I have a Visual Studio solution with multiple projects, and I want to move a view that uses a controller from one project to a new project in the same solution, but I'm not sure if I have to move my controller. Currently, the controller and the view live in the same project. The view attaches the controller to the DOM using the ng-controller directive.

I'm not sure how ng-controller finds a controller. In every example I've seen and throughout the application I am working with, ng-controller always equals a controller name with no path to it, e.g., ng-controller="MyController". So, how does it know where to locate the controller?

For example, this is an anonymized snippet from my cshtml view:

@model MyProject.ViewModel.Panel.MyViewModel
<div id="Panel"
    ng-controller="MyController" 
    ng-init="MyController.initValues(@Model.Id,
    ...,
    ...)">
</div>

How does ng-controller find MyController, and if I move its view to a different project than the project they currently share, will it still find MyController?


Solution

  • <div ng-app="myApp" ng-controller="myCtrl">
    
    Full Name: {{firstName + " " + lastName}}
    
    </div>
    
    <script>
    
    var app = angular.module('myApp', []);
    
    // **** AngularJs will find it or look for it from where ever              ****
    // **** you define in the app.controller('xxxx') variable                  ****
    // **** which is alias to a Namespace 'myApp'                              **** 
    
    app.controller('myCtrl', function($scope) {
        $scope.firstName = "John";
        $scope.lastName = "Doe";
    });
    
    </script>