【问题标题】:Invalid data bind in the multi controller page多控制器页面中的数据绑定无效
【发布时间】:2015-10-17 20:15:03
【问题描述】:

这是我的代码:

索引.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>

script.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);
    }
}]);

route.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 制作路线,它会在我转到这条路线时起作用。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    原因是您在渲染including.html 时使用了ng-include。与您使用 ng-include 时一样,它会创建一个子范围,该子范围在原型上继承自父范围。

    在这种情况下定义ng-model 时需要遵循dot rule,这将倾向于使用Prototypal Javascript Inheritance & 将从对象中获取值。

    您需要定义一个名为model 的对象,其中将包含各种属性,例如$scope.model = { 'field': '' }

    标记

    <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);
        }
    }]);
    

    编辑

    您也可以编写自己的指令,例如 ng-include,它从 URL 加载模板,但不会创建子作用域。

    你可以参考这个方法here

    【讨论】:

    • 是否有其他方法可以做到这一点?
    • @nuclearkote 看看编辑..我添加了编辑部分
    • 感谢您对错误的解释,但我找到了另一种修复方法。我用一个简单的指令替换了 ng-include,现在它运行良好。 app.directive('test', function() { return { restrict: 'E', templateUrl: 'including.html', } });
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多