Shlomi Schwartz Shlomi Schwartz - 1 year ago 151
AngularJS Question

AngularJS - losing scope when using ng-include

I have this module routes:

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

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


function HomeCtrl($scope, $location, $window, $http, Common) {
$scope.views = {

$scope.addLine = function () {
$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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download