Javascript 多控制器页面中的数据绑定无效
这是我的代码: index.html: route.html:Javascript 多控制器页面中的数据绑定无效,javascript,angularjs,Javascript,Angularjs,这是我的代码: index.html: route.html: <div> hello world <div>{{hello}}</div> <ng-include src="'including.html'" ng-controller="IncController"></ng-include> </div> 你好,世界 {{你好}} include.html: <input type
<div>
hello world
<div>{{hello}}</div>
<ng-include src="'including.html'"
ng-controller="IncController"></ng-include>
</div>
你好,世界
{{你好}}
include.html:
<input type='text' ng-model='field'/>
<input type='button' ng-click='test()'/>
当我单击按钮时,test()函数正在调用,但字段始终为空。
如果我为include.html创建路由,则当我转到此路由时,它会工作。原因是您在呈现
include.html
时使用了ng include
。与使用ng include
时一样,它创建了一个子作用域,该子作用域通常从父作用域继承
在这种情况下,定义ng模型时需要遵循dot规则
,这将倾向于使用&从对象中获取值
您需要定义一个名为model
的对象,其中包含各种属性,如$scope.model={'field':'}
标记
<input type='text' ng-model='model.field'/>
<input type='button' ng-click='test()'/>
编辑
您也可以编写自己的指令,如ng include
,从URL
加载模板,但它不会创建子范围
您可以参考此方法是否有其他方法可以做到这一点?@nuclearkote查看编辑..我添加了编辑部分谢谢您对错误的解释,但我找到了另一种方法来修复它。我用一个简单的指令替换了ng include,现在它运行良好。指令('test',function(){return{restrict:'E',templateUrl:'include.html',}});
<input type='text' ng-model='field'/>
<input type='button' ng-click='test()'/>
<input type='text' ng-model='model.field'/>
<input type='button' ng-click='test()'/>
app.controller('IncController', ['$scope', function($scope) {
$scope.model = { 'field': '' };
$scope.test = function() {
console.log('test=' + $scope.model.field);
}
}]);