【问题标题】:ng-model on select in AngularJS + JQM works partly在 AngularJS + JQM 中选择的 ng-model 部分工作
【发布时间】:2013-07-20 11:41:15
【问题描述】:

适用于基于 AngularJS、JQuery Mobile 和 JQuery Mobile Angular Adapter 的应用。

当我在带有 data-role="page" 的标签上设置 ng-controller 时,选择标签上的 ng-model 可以完美运行:

<body ng-app>
    <div data-role="page" id="product" ng-controller="Controller">
        <div data-role="content">
            <select ng-model="color" ng-options="c for c in colors"></select>
            <button ng-click="Print()">print</button>

http://jsfiddle.net/ilya7u/Ddt7G/

当body标签中存在ng-controller时,通过ng-model与select标签关联的变量保持不变:

<body ng-app ng-controller="Controller">
    <div data-role="page" id="product">
        <div data-role="content">
            <select ng-model="color" ng-options="c for c in colors"></select>

http://jsfiddle.net/ilya7u/qgbj2/

为什么以及如何解决?我想在多页应用中使用一个控制器!

【问题讨论】:

  • 这似乎在 Chrome 中运行良好。你是如何测试的?
  • 在Chrome、Safari下测试!打开jsfiddle.net/ilya7u/qgbj2,将颜色从红色变为白色或黑色,然后检查$scope.color。 $scope.color 将是“红色”!

标签: jquery-mobile angularjs


【解决方案1】:

在页面的 html 中包含 ng-app 将解决问题

试试

<html ng-app="myModule">
<body ng-controller="Controller">
    <div id="product" >
        <div data-role="content">
            <select ng-model="color" ng-options="c for c in colors"></select>
            <button ng-click="Print()">print</button>
        </div>
    </div>
</body>
</html>

并将控制器更改为

var myApp = angular.module('myModule',[]);
myApp.controller('Controller', function($scope) {
   $scope.colors = ['red', 'black', 'white'];
    $scope.color = $scope.colors[0];

    $scope.Print = function () {
        alert($scope.color);
    };
});

这里更新了小提琴http://jsfiddle.net/qgbj2/2/

【讨论】:

  • 很遗憾,一切都没有改变
  • 是的,它有效!但是当我在
    ng-model 中设置 JQM attr data-role="page" 时保持不变!
【解决方案2】:

所以看起来这里真的有两个作用域。该页面有自己的范围,但 Print 在父范围内。我更新了小提琴以显示颜色确实发生了变化,但 Print 中的 $scope.color 没有:http://jsfiddle.net/qgbj2/6/

为了解决这种特殊情况,我会从 DOM 中将颜色传递给 Print:

    <body ng-app ng-controller="Controller">
        <div data-role="page" id="product">
            <div data-role="content">
                <select ng-model="color" ng-options="c for c in colors"></select>
                <button ng-click="Print(color)">print</button>
            </div>
        </div>
    </body>

我目前没有想到这种多范围情况的通用解决方案。

【讨论】:

  • 你是对的,谢谢!我找到了有关此的文档。我的错误 - 在阅读文档之前使用。例如:“jquery mobile 的每个页面都有一个单独的范围。”和解决方案:“对于页面之间的通信,请使用 ngm-shared-controller 指令”
猜你喜欢
  • 2018-04-20
  • 2023-03-18
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多