2

我在应用程序中的一个模块中使用了 angularjs。我想更新页面上各个位置的 UI,以便所有 ui 组件随着模型值的变化而同步工作。

这是我的html-

<fieldset ng-controller="controller1" >
        <legend>Divs with common controller</legend>
        <div style="background-color:#eee;padding:3px;">
            <input type="text" ng-model="Model1" />
        </div>
        <div style="background-color:#eee;padding:3px;">
            <input type="text" ng-model="Model1" />
        </div>
    </fieldset>

    <fieldset ng-controller="controller1" >
        <legend>Divs with common controller</legend>
        <div style="background-color:#eee;padding:3px;" ng-controller="controller2">
            <input type="text" ng-model="Model1" />
            <input type="text" ng-model="Model2" />
        </div>
        <div style="background-color:#eee;padding:3px;">
            <input type="text" ng-model="Model1" />
        </div>
    </fieldset>

和我的 javascript -

var testApp = angular.module('testApp',[]);
        var mainApp = angular.module('mainApp',['testApp']);

        testApp.controller("controller1",['$scope',function($scope){
            $scope.Model1 = "testText";
        }]);

        testApp.controller("controller2",['$scope',function($scope){
            $scope.Model2 = "testText2";
        }]);
        angular.bootstrap(document, ['mainApp']);

在第一个字段集的 html 中,它工作正常。但在第二个字段集中它不是。所以谁能告诉我如何在第二个字段集中实现第一个字段集的功能。谢谢。

4

4 回答 4

1

使用$rootScope而不是$scope

于 2014-12-23T13:01:36.273 回答
0

它不起作用,因为您为 controller1 创建了 2 个单独的范围/实例

<div>
   // Root scope
   <div ng-controller="controller1">
      // Child scope A
      // scope = new controller1();
   </div>
   <div ng-controller="controller1">
      // Child scope B
      // scope = new controller1();
   </div>
</div>

您可以通过$rootScope直接使用或创建服务来解决此问题。推荐的方法是尽可能避免$rootScope使用服务。

价值可能是创建服务的最简单方法。请注意,您也可以使用.service.factory。在有关服务的文档中阅读更多信息。

testApp.value('myValue', {
    data: 'testText'
});

我在这里使用了一个对象,因此我们可以将其用作对值的引用,这对于在控制器之间共享数据很重要。如果您想知道原因,请阅读有关引用和值类型的更多信息。

现在将此服务注入您的控制器并改用此数据:

testApp.controller("controller1",['$scope', 'myValue',function($scope, myValue){
    $scope.Model1 = myValue;
}]);

在视图上,我们需要更新绑定到服务的引用:

<input type="text" ng-model="Model1.data" />

JSFIDDLE

于 2014-12-23T13:46:58.633 回答
0

您可以使用 ng-controller="controller2" 来进行特定输入吗?尝试这个

<div style="background-color:#eee;padding:3px;"> <input type="text" ng-model="Model1" /> <input type="text" ng-model="Model2" ng-controller="controller2" /> </div>

于 2014-12-23T09:27:52.810 回答
-1

使用点!没有“.”的 ng-model 不好。请阅读这篇文章 AngularJS中范围原型/原型继承的细微差别是什么? 该问题已在此处进行了全面描述。

于 2014-12-23T14:00:47.013 回答