用另一个模型过滤一个控制器的内容(AngularJS)

时间:2014-06-18 19:42:54

标签: javascript angularjs angularjs-model

我有类似的东西:

<div ng-controller="ControllerA">
    <input type="text" id="search_form" value="Search" ng-model="searchModel" />
</div>

<div ng-controller="ControllerB">
    <ul>
        <li ng-repeat="item in items | filter:searchModel">{{item}}</li>
    </ul>
</div>

但是当我在输入栏中搜索时,它不会影响我的列表。如何让我的模型从一个控制器影响另一个控制器的内容?

感谢。

修改

ControllerAControllerB彼此完全隔离,我希望保持这种方式。如果我需要与其他控制器共享模型,我将如何使用$rootScope来执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以使用service在控制器之间共享数据。 使用角度所需的factory功能定义service

以下是我发现here并进行简单谷歌搜索的示例。

<!doctype html>
<html ng-app="project">
<head>
    <title>Angular: Service example</title>
    <script src="http://code.angularjs.org/angular-1.0.1.js"></script>
    <script>
var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() {  
    return {
        thing : {
            x : 100
        }
    };
});

function FirstCtrl($scope, theService) {
    $scope.thing = theService.thing;
    $scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {   
    $scope.someThing = theService.thing; 
    $scope.name = "Second Controller!";
}
    </script>
</head>
<body>  
    <div ng-controller="FirstCtrl">
        <h2>{{name}}</h2>
        <input ng-model="thing.x"/>         
    </div>

    <div ng-controller="SecondCtrl">
        <h2>{{name}}</h2>
        <input ng-model="someThing.x"/>             
    </div>
</body>
</html>

答案 1 :(得分:0)

如果你有一个需要共享的模型,你应该使用一种服务,控制器可以访问数据并知道任何变化