Search code examples
javascriptangularjsangularjs-ng-includeng-controller

AngularJs - Using ng-controller with ng-include


This works:

<div ng-include="'login.html'" flex ng-if="!loggedIn" ng-controller="LoginController"></div>

However, this doesn't ({{test}} outputs nothing):

<ng-include src="'login.html'" flex ng-if="!loggedIn" ng-controller="LoginController"></ng-include>

Is there any reason? Or is it a bug?

login.html:

<p>{{test}}</p>

LoginController:

function LoginController($scope){
    $scope.test = 'login';
}

Solution

  • I'm not exactly sure where "loggedIn" is defined, but when I define it on a parent controller, both syntaxes work as expected.

    Plunkr

    <div ng-controller="PrntCtrl">
          <div ng-include="'test.html'" flex ng-if="!loggedIn" ng-controller="TestCtrl"></div>
          <ng-include src="'test.html'" flex ng-if="!loggedIn" ng-controller="TestCtrl"></ng-include>
        </div>
    

    Some questions to consider: What version of angular are you using? How is your app defined and how is the controller registered with the app? Where is "loggedIn" defined?