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.

2
  • 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 Commented Jan 27, 2014 at 8: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. Commented Jan 27, 2014 at 10:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.