这是我的代码:
index.html:
<head>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
脚本.js:
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'route.html',
controller: 'RouteController',
}).otherwise('/');
}]);
app.controller('RouteController', ['$scope', function($scope) {
$scope.hello='world';
}]);
app.controller('IncController', ['$scope', function($scope) {
$scope.field = '';
$scope.test = function() {
console.log('test=' + $scope.field);
}
}]);
路线.html:
<div>
hello world
<div>{{hello}}</div>
<ng-include src="'including.html'"
ng-controller="IncController"></ng-include>
</div>
包括.html:
<input type='text' ng-model='field'/>
<input type='button' ng-click='test()'/>
当我单击按钮 test() 函数时,正在调用,但字段始终为空。 如果我为 include.html 创建路线,那么当我转到此路线时它会起作用。
最佳答案
原因是您在渲染 include.html
时使用了 ng-include
。当您使用 ng-include 时,它会创建一个子作用域,该子作用域通常是从父作用域继承的。
在这种情况下,您在定义 ng-model
时需要遵循点规则
,这往往会使用 Prototypal Javascript Inheritance
& 将从对象中获取值。
您需要定义一个名为 model
的对象,其中包含各种属性,例如 $scope.model = { 'field': '' }
标记
<input type='text' ng-model='model.field'/>
<input type='button' ng-click='test()'/>
Controller
app.controller('IncController', ['$scope', function($scope) {
$scope.model = { 'field': '' };
$scope.test = function() {
console.log('test=' + $scope.model.field);
}
}]);
编辑
您还可以编写自己的指令,例如 ng-include
,它从 URL
加载模板,但不会创建子作用域。
可以引用这个方法here
关于javascript - 多 Controller 页面中的数据绑定(bind)无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33191154/