1

对于基于 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/

当 ng-controller 出现在 body 标签中时,通过 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/

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

4

2 回答 2

2

在页面的 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/

于 2013-07-20T12:36:23.583 回答
0

所以看起来这里真的有两个范围。该页面有自己的范围,但 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>

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

于 2013-07-21T13:38:36.887 回答