18

First and foremost, the plunker: http://plnkr.co/edit/v1uTz5

This is a working demo of the issue I am running into.

I have a ng-include to include a partial.

Inside the partial I have an text input with ngModel AND directive.

The model updates accordingly inside the include, but any interaction outside the include is ignored. The {{test}} outside the include doesn't update, but the {{test}} inside does.

The directive, when called, handles the enter key and calls the correct scope and function. However, the $scope.test variable has never been updated, but $scope.testFinal is updated and the ng-include template renders it appropriately. Trying to reset the $scope.test model does not work either.

Am I missing something here? Or is this a bug with the directive or with the ng-include?

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
Tim Withers
  • 12,072
  • 5
  • 43
  • 67

3 Answers3

31

Instead of using a primitiive to define the variable, make it an object.

$scope.model={test:''};

Directives create their own scope for each item. When you equate a primitive to a new scope variable, it has no binding to the original, however when original is an object, a reference is created , not a copy, and changes made in one will reflect in the other

Simple explanatory example:

var a ='foo';
var b= a;
/* now change a*/
a='bar';
alert( b) // is still 'foo'

now do the same with object:

var obj_1= {a:'foo'};
var obj_2=obj_1;
/* now change obj_1.a*/
obj_1.a='bar';
alert( obj_2.a) // change to obj_1 will also change obj_2 and alert returns "bar"*/

Your Plunker Modified

Read this article on angular wiki for more detailed explanation

7hi4g0
  • 3,729
  • 4
  • 22
  • 32
charlietfl
  • 170,828
  • 13
  • 121
  • 150
5

John Lindquist has a video about it. Although he doesn't quite explains why you need to use an object.

Basically every time there is a new non-isolated scope, every property of the parent scope is copied to the new scope and, as @charlietfl explained, copying a primitive type really creates a "copy" but with objects what you get is a reference, hence the changes are global.

7hi4g0
  • 3,729
  • 4
  • 22
  • 32
1

ng-include creates its own scope and it is different than outer scope. Use this.test instead of $scope.test inside ng-include template. It will work properly.

Rahul Jha
  • 874
  • 1
  • 11
  • 28