2

我正在尝试更新然后获取 AngularJs 工厂的更新值,我在一个范围内设置值并尝试在另一个范围内获取它,我正在设置一个工厂来处理我的应用程序中的弹出消息,而不是重复我自己我只想要一个工厂来处理这些消息。

myApp.factory('msg',function ($modal) {
    factory = {};

    factory.text = '';
    factory.modal;
    factory.response;

    factory.window = function () {
        this.modal = $modal.open({
            templateUrl:'partials/message/confirm.html',
            controller:'cms'
        });
    }

    factory.setText = function (text) {
        this.text = text;
    }

    factory.getResponse = function () {
        return this.response;
    }

    factory.confirm = function () {
        this.modal.close();
        this.response = true;
    }

    factory.cancel = function () {
        this.modal.close();
        this.response = false;
    }

    factory.confirmSave = function () {
        this.text = 'save';
        this.window();
    }

    factory.confirmUpdate = function () {
        this.text = 'update';
        this.window();
    }

    factory.confirmDelete = function () {
        this.text = 'delete';
        this.window();
    }


    return factory;
});

用户控制器

myApp.controller('users',function ($scope,$location,$http,msg) {
    $http.get('api/v1/users')
    .success(function (data,status) {
        $scope.user = data;
    })
    .error(function (data,status) {
        $location.path('/login');
    });

    $scope.showWrite = function () {
        $scope.write = true;
    }

    $scope.closeWrite = function () {
        $scope.write = false;
        $scope.newUser = '';
    }

    $scope.save = function () {
        $http.post('api/v1/users/store',$scope.newUser)
        .success(function (data,status) {

            $scope.user.unshift({
                first_name: $scope.newUser.first_name,
                last_name: $scope.newUser.last_name,
                email: $scope.newUser.email,
                role: $scope.newUser.role
            });

            $scope.write = false;
            $scope.newUser = '';
        })
        .error(function (data,status) {
            alert('failed');
        });
    }

    $scope.confirmDelete = function (index,id) {
        msg.confirmDelete();
        if(msg.getResponse() === true){
            $http.get('api/v1/users/destroy/'+id)
            .success(function (data,status) {
                $scope.user.splice(index,1);
            })
            .error(function (data,status) {
                alert('failed');
            });
        };
        console.log(msg.getResponse());
    }

    $scope.showUserInfo = function () {

    }

});
4

1 回答 1

1

您提供的代码似乎工作正常,问题出在其他地方,可能在cms控制器或confirm.html模板中。我和你的工厂做了一个plunker,你可以在那里看到它。

索引.html

<div ng-controller="ctrl1">
  <button ng-click="msg.confirmSave()">confirm save</button>
  <span ng-if="msg.getResponse() !== undefined">Response: {{msg.getResponse()}}</span>
</div>

确认.html

<h1>{{msg.text}}</h1>
<button ng-click="msg.confirm()">Confirm</button>
<button ng-click="msg.cancel()">Cancel</button>

JavaScript

angular.module('app',['ui.bootstrap']).
  controller('cms', ['$scope', 'msg', function($scope, msg){
    $scope.msg = msg;
  }]).
  controller('ctrl1', ['$scope', 'msg', function($scope, msg) {
    $scope.msg = msg;
  }]).
  factory('msg',['$modal', function ($modal) {
    // The same code as in the question
  }]);

一些技巧:

  • 使用var factory = {};而不是factory = {}为了声明局部变量而不是factory偶尔覆盖全局变量。
  • factory.modal;并且factory.response;不要factory像你期望的那样在 object 中声明相关属性,而是返回undefined,所以只需删除它们,因为它们没用
  • factory.setTextfacory.getResponse是多余的,因为factory.textfactory.response是 的公共属性factory。如果您想让它们对工厂私有,请将它们声明为var text;andvar response;并相应地更改访问器方法。getText在这种情况下,添加到您的工厂也很有用。
  • 如果您打算factory.modal仅从您的工厂访问,最好将其封装到您的工厂(使其私有),如上一个项目中所述。
  • window仅公开工厂的公共 API(例如不公开)

应用所有提示后,您的工厂可能如下所示:

factory('msg',['$modal', function ($modal) {
    var text = '',
        modal,
        response;

    function window () {
        modal = $modal.open({
            templateUrl:'confirm.html',
            controller:'cms'
        });
    }

    return {
      setText: function (_text_) {
        text = _text_;
      },
      getText: function() {
        return text;
      },
      getResponse: function () {
        return response;
      },
      confirm: function () {
        modal.close();
        response = true;
      },
      cancel: function () {
        modal.close();
        response = false;
      },
      confirmSave: function () {
        text = 'save';
        window();
      },
      confirmUpdate: function () {
        text = 'update';
        window();
      },
      confirmDelete: function () {
        text = 'delete';
        window();
      }
    };
  }]);

这是一个笨蛋

编辑:

用控制器代码更新帖子后,我一切都清楚了:真正的问题是您confirmDelete()同步使用,但它是异步的(因为将来返回值,一旦用户单击确认或取消)!处理异步人员 angular 有一个$q服务。为了使用它,您应该在 and 中创建延迟对象,factory.confirmSave()返回它的承诺并在 and 中解决/拒绝它。一旦 promise 被解决或拒绝,您可以从中获取值或直接将其作为相关回调的参数。factory.confirmUpdate()factory.confirmDelete()factory.confirm()factory.cancel()factory

工厂

function confirmDelete() {
  deferred = $q.defer();
  text = this;
  window();
  return deferred.promise;
}

控制器

msg.confirmDelete().then(function(value) {
    // Resolved
    $scope.response = value;
}, function(value) {
    // Rejected
    $scope.response = value;
});

完整示例请参见以下plunker

于 2014-04-19T11:34:34.427 回答