简体   繁体   中英

AngularJS - ng-include ng-controller and scope not binding

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM