6

I have the following main view

<div ng-include="'otions.html'"></div>

and options.html has the following

<div ng-controller="OptionsController">Options</div>
<input type="text" ng-model="keyword" value="{{keyword}}" />
<button ng-click="search()">Search</button>

But "keyword" is not binding to the scope in OptionsController.

app.controller('OptionsController', 
              ['$scope', function($scope) {

  $scope.keyword = "all";
  $scope.search = function() {
    console.log("hello")
  };

}]);

when I click on the button, I don't see hello and the keyword all doesn't appear in the input text.

I tried moving the ng-controller part as follows

<div ng-controller="OptionsController" ng-include="'otions.html'"></div>

And things work as expected.

I read through the answers in AngularJS - losing scope when using ng-include - and I think my problem is related, but just need some more explanation to undertstand what's going on.

Community
  • 1
  • 1
ericbae
  • 9,604
  • 25
  • 75
  • 108
  • Not sure if it's a typo here but also in your source: the file you're including is references as `otions.html` instead of `options.html` – thomaux Jan 27 '14 at 08:01
  • In your source you specify ng-controller for the first `div` only, so your input and button are not in the scope of your controller. Probably it is a typo. If not then it could be a reason. – GRaAL Jan 27 '14 at 10:18

2 Answers2

7

You should write options.html like this:

<div ng-controller="OptionsController">Options
<input type="text" ng-model="keyword" value="{{keyword}}" />
<button ng-click="search()">Search</button>
</div>

OptionsController should be put in the outer html element.

Community
  • 1
  • 1
Andy Ma
  • 328
  • 3
  • 7
  • Good catch, I missed that. In the original html the input it outside of the div marked with the controller so the scope variable doesn't exist. – Miniver Cheevy Oct 09 '14 at 18:01
0

i have face same problem,

Under main tag it will be work fine but, When bind some data to nav.html it not work.

find this link

AngularJS - losing scope when using ng-include

inside include its work child scope. better option to create custom directive its easy solution

Community
  • 1
  • 1
Ashish Kadam
  • 1,439
  • 2
  • 13
  • 18