Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 846
ericbae Avatar asked Jan 27 '14 07:01

ericbae


People also ask

Does Ng include create a new scope?

ngInclude creates a new child scope which inherits scope values from the parent controller.

What is required with Ng include directive?

The ng-include directive includes HTML from an external file. The included content will be included as childnodes of the specified element. The value of the ng-include attribute can also be an expression, returning a filename. By default, the included file must be located on the same domain as the document.

What is Controlleras in AngularJS?

In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.

What does ng controller do?

The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.


1 Answers

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.

like image 65
Andy Ma Avatar answered Oct 20 '22 13:10

Andy Ma