使用服务的控制器之间的角度共享数据

时间:2013-08-07 18:54:57

标签: javascript angularjs

我正在使用服务在控制器之间共享数据。 在第一个控制器中,我调用这样的函数:

muscleGroupService.setState(true);

以下是服务中的功能代码:

  var state;

  function setState(x) {
        state = x;
    }

x变为真,但由于某种原因状态不成立,它保持未定义。

我该如何解决这个问题?

修改

我相信我已经设法找到问题所在,但我不确定如何解决它。

在Index.html中我有这行代码:

<div class="modal fade" ng-include src="'/Content/Templates/Modals/Admin/ModalMuscleGroup.html'"  id="addModal"> </div>

一旦我进入页面ng-include包括ModalMuscleGroup.html和模态窗口的控制器。

当我做smth时,我模态widnow控制器。像这样:

muscleGroupService.isItemBeingUpdated()

它返回undefined,因为我不看变量状态。

我相信这可以修复使用$ rootScope和$ rootScope。$ broadcast和$ rootScope。$ on。没有使用$ rootScope还有其他方法吗?

修改2

这是代码:

Ctrl1的一部分(应该将数据发送到服务):

$scope.updateItem = function (item) {
    muscleGroupService.setState(true);
    muscleGroupService.setItemForUpdate(item);
};

重新定位服务部分:

app.angularModule.service('muscleGroupService', function(breeze, logger) {


    breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);

    var serviceName = "/breeze/MuscleGroup";

    var manager = new breeze.EntityManager(serviceName);

    manager.enableSaveQueuing(true);

    var removeItem = breeze.core.arrayRemoveItem;

    var items = [];
    var state;

    var itemBeingUpdated;


    return {

        setState: function(x) {
            state = x;
        },

        isItemBeingUpdated : function() {
            return state;
        },

        setItemForUpdate : function(item) {
             itemBeingUpdated = item;
        },

        getItemBeingUpdated : function() {
            return itemBeingUpdated;
        },

        updateItem : function() {
            if (itemBeingUpdated.entityAspect.entityState.isModified()) {
                saveChanges();
            }
        },

这是模态控制:

app.angularModule.controller('AdminMuscleGroupModalCtrl', function ($scope, breeze, muscleGroupService) {

    $scope.init = function () {
        if (muscleGroupService.isItemBeingUpdated() == true) {
            $scope.itemBeingUpdated = muscleGroupService.getItemBeingUpdated();  
            $scope.NewName = itemBeingUpdated.Name;
            $scope.NewDesc = itemBeingUpdated.Description;
        }
    };

    $scope.init();
});

这是Ctrl1的html的一部分:

    <tbody>
                        <tr data-ng-repeat="item in items">
                            <td>{{item.Name}}
                            </td>
                            <td>{{item.Description}}
                            </td>
                            <td> <button class="btn btn-primary" data-ng-click="updateItem(item)" data-toggle="modal" href="#addModal"><i class="glyphicon glyphicon-pencil"></i> Edit</button>
     </tr>
                    </tbody>

 <div class="modal fade" ng-include src="'/Content/Templates/Modals/Admin/ModalMuscleGroup.html'"  id="addModal"> </div>

和modal html:

<div class="modal-body">
            <form class="form-horizontal">
                <div class="form-group">
                    <label for="inputName" class="col-lg-2 control-label">Name</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" data-ng-model="NewName" id="inputName" placeholder="Name">
                    </div>
                </div>
                <div class="form-group">
                    <label for="inputDesc" class="col-lg-2 control-label">Description</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" data-ng-model="NewDesc" id="inputDesc" placeholder="Description">
                    </div>
                </div>
            </form>
        </div>

5 个答案:

答案 0 :(得分:4)

尝试按以下方式定义您的功能:

myApp.factory('myService', function(){
    var state;
    return {
        setState:function(x){
            state = x;
        }
    }
});

答案 1 :(得分:0)

尝试

this.state = null;
that = this;
function setState(x) {
    that.state = x;
}

答案 2 :(得分:0)

您是否尝试过this.state = x

答案 3 :(得分:0)

我设法解决了我的问题,这个答案有所帮助:link

所以我做了类似的事情:

$scope.$watch( function() { return muscleGroupService.getAction(); }, function() {
        if (muscleGroupService.getAction() == "edit") {
            $scope.$watch(function () { return muscleGroupService.getItemForUpdate(); }, function () {
                $scope.action = "edit";
                $scope.ItemForUpdate = muscleGroupService.getItemForUpdate();
                $scope.NewName = $scope.ItemForUpdate.Name;
                $scope.NewDesc = $scope.ItemForUpdate.Description;
            });
        } else {
            $scope.action = "add";
            $scope.NewName = "";
            $scope.NewDesc = "";
        }
    }); 

不确定这是否是最佳做法,但确实有效:)

答案 4 :(得分:0)

角度服务本质上是构造函数,所以在你注入服务的幕后你得到以下调用的结果:

new serviceFnc();

Angular只会运行一次(单例),然后在你注入服务的任何地方为你提供该对象

因此,对于您的示例,您可以执行以下操作:

myApp.service('muscleGroupService', function(){
//again this function will be newed once
var service = this;

//You dont even need a function just inject muscleGroupService in your controllers and set muscleGroupService.state = true || false
service.state = false;

});

有关服务/工厂的详细信息,请参阅此SO Post

相关问题