javascript - 多 Controller 页面中的数据绑定(bind)无效

标签 javascript angularjs

这是我的代码:

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/

相关文章:

javascript - 如何将一个事件监听器附加到多个对象?

javascript - 在Google Charts LineChart中绘制多个DataTable

javascript - 如何在 angularjs 中使用 if 构造 Controller 变量

javascript - Karma 测试未完成

javascript - 在 jquery.load 页面中使用 angularjs

javascript - 切换类以显示/隐藏导航在 Chrome for Android 4.2 (v31) 中不起作用

php - 使用 IOS/Android 等时将 ondblclick 更改为 onclick 事件

javascript - Ionic 4 D3 样式与 scss 类

css - Jspdf - fromHtml() - 单页 Pdf

javascript - 使用 AngularJS 和 ng-submit 记住密码