一尘不染

在AngularJS Services中处理数据绑定

angularjs

我试图弄清楚当我的数据存储在服务中时如何正确处理绑定。

如果将服务放到$ scope中,然后让模板直接绑定到它中,我可以使事情工作,但这似乎是一个糟糕的主意。

我基本上希望拥有它,以便我的视图/控制器能够轻松地将状态更改为服务,并将其反映到各处。

感觉我应该可以执行以下操作,但是不起作用(http://jsfiddle.net/aidankane/AtRVD/1/)。

的HTML

<div ng-controller="MyCtl">
    <select ng-model="drawing" ng-options="d.file for d in drawings"></select>
</div>
<div ng-controller="MyOtherCtl">
    {{ drawing }}
</div>

JS

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

myApp.factory('myService', function(){
    var me = {
        drawings: [{'file':'a'}, {'file':'b'}]
    };
    // selected drawing
    me.drawing = me.drawings[0];
    return me;
});

function MyCtl($scope, myService){
    // can do:
    // $scope.mys = myService;
    // and then in html ng-model="mys.drawing"
    // but that seems wrong

    $scope.drawings = myService.drawings;
    $scope.drawing = myService.drawing;

    // can I not do this? it doesn't seem to work anyway...
    $scope.$watch('drawing', function(drawing){
        myService.drawing = drawing;
    });
}

function MyOtherCtl($scope, myService){
    $scope.drawing = myService.drawing;
}

MyCtl.$inject = ['$scope', 'myService'];
MyOtherCtl.$inject = ['$scope', 'myService'];

阅读 333

收藏
2020-07-04

共1个答案

一尘不染

您可以使用$watch并传递一个函数来绑定服务:

$scope.$watch( function () { return myService.drawing; }, function ( drawing ) {
  // handle it here. e.g.:
  $scope.drawing = drawing;
});

然后$scope.drawing在您的模板中使用,它们将自动更新:

<div ng-controller="MyOtherCtl">
  {{ drawing }}
</div>
2020-07-04