Shlomi Schwartz Shlomi Schwartz - 3 months ago 53
AngularJS Question

AngularJS - losing scope when using ng-include

I have this module routes:

var mainModule = angular.module('lpConnect', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {template:'views/home.html', controller:HomeCtrl}).
when('/admin', {template:'views/admin.html', controller:AdminCtrl}).
otherwise({redirectTo:'/connect'});
}]);


Home html:

<div ng-include src="views.partial1"></div>


partial1 html:

<form ng-submit="addLine()">
<input type="text" ng-model="lineText" size="30" placeholder="Type your message here">
</form>


HomeCtrl:

function HomeCtrl($scope, $location, $window, $http, Common) {
...
$scope.views = {
partial1:"views/partial1.html"
};

$scope.addLine = function () {
$scope.chat.addLine($scope.lineText);
$scope.lines.push({text:$scope.lineText});
$scope.lineText = "";
};
...
}


in the addLine function $scope.lineText is undefined, this can be resolved by adding ng-controller="HomeCtrl" to partial1.html , however it causes the controller to be called twice, what am I missing here?

Answer

This is because of ng-include which creates a new child scope, so $scope.lineText isn't changed. I think that this refers to the current scope, so this.lineText should be set.

Comments