javascript AngularJS - ng-include ng-controller 和范围未绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21375590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - ng-include ng-controller and scope not binding
提问by ericbae
I have the following main view
我有以下主要观点
<div ng-include="'otions.html'"></div>
and options.html has the following
和 options.html 有以下内容
<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.
但是“关键字”并未绑定到 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.
当我点击按钮时,我看不到hello
并且关键字all
没有出现在输入文本中。
I tried moving the ng-controller part as follows
我尝试按如下方式移动 ng-controller 部分
<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 thinkmy problem is related, but just need some more explanation to undertstand what's going on.
我通读了AngularJS 中的答案——使用 ng-include 时失去了范围——我认为我的问题是相关的,但只需要更多的解释来了解发生了什么。
回答by Andy Ma
You should write options.html like this:
您应该像这样编写 options.html:
<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.
OptionsController 应该放在外部 html 元素中。
回答by Ashish Kadam
i have face same problem,
我有同样的问题,
Under main tag it will be work fine but, When bind some data to nav.html it not work.
在主标签下它会正常工作,但是当将一些数据绑定到 nav.html 时它不起作用。
find this link
找到这个链接
AngularJS - losing scope when using ng-include
AngularJS - 使用 ng-include 时丢失范围
inside include its work child scope. better option to create custom directive its easy solution
里面包括它的工作子范围。创建自定义指令的更好选择其简单的解决方案