【问题标题】:ng-model not working inside ng-includeng-model 在 ng-include 中不起作用
【发布时间】:2015-12-22 21:20:59
【问题描述】:

我是 angularjs 的初学者,目前我正面临 ng-include 的问题。

我有一个使用部分的测试应用程序。 这是我的代码。

<html ng-app ="TextboxExample">
    <head>
        <title>Settings</title>
        <script src="angular.js"></script>
  </head>

    <body ng-controller="ExampleController">
        <div ng-include src = "'view.html'"></div>
        <script>
          angular.module('TextboxExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.textboxVal = 'fddfd';

              $scope.ReadGeneralSettings = function() {
                alert($scope.textboxVal);
              }
              $scope.ResetGeneralSettings = function() {

                $scope.textboxVal = 'fddfd';
              }

            }]);
        </script>
        <button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
        <button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>



    </body>
</html>

部分代码view.html是

<input type="text" ng-model="textboxVal">

由于某种原因,当我在文本框中输入值时,设置为 ng-model 的 textboxVal 不会得到更新。 但是如果我不使用 ng-include 并直接将 view.html 的内容添加到主 html 文件中,这会很好。 请帮忙。

谢谢 苏尼尔

【问题讨论】:

  • ng-include 创建一个新范围
  • 好的,我可以让它工作吗?
  • 在下面查看我的答案

标签: javascript angularjs angularjs-ng-include


【解决方案1】:

使用 $parent 访问控制器的作用域

Demo

<input type="text" ng-model="$parent.textboxVal">

【讨论】:

    【解决方案2】:

    问题在于ngInclude 创建了新范围,因此您在部分模板内部使用ngModel 定义的模型适用于本地范围值,而外部ExampleController 看不到它。

    简单的解决方案是使用原型链的作用域对象,然后内部作用域将从外部作用域继承并使用模型值:

    <body ng-controller="ExampleController">
        <div ng-include src = "'view.html'"></div>
        <script>
          angular.module('TextboxExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.model.textboxVal = 'fddfd';
    
              $scope.ReadGeneralSettings = function() {
                alert($scope.model.textboxVal);
              }
              $scope.ResetGeneralSettings = function() {
                $scope.model.textboxVal = 'fddfd';
              }
    
            }]);
        </script>
        <button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
        <button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
    
    </body>
    

    然后将其部分用作

    <input type="text" ng-model="model.textboxVal">
    

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 1970-01-01
      • 2017-02-07
      • 2018-03-27
      • 2016-09-12
      • 2018-08-29
      • 1970-01-01
      • 2016-01-20
      相关资源
      最近更新 更多