为什么不能AngularJS视图发送数据到这个可重用的服务? [英] Why can't AngularJS view send data to this re-usable service?

查看:127
本文介绍了为什么不能AngularJS视图发送数据到这个可重用的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是AngularJS应用程序需要重新使用多个自定义对象。我关心创建杂乱,多余的code,它是很难维持的,让我感动的可重复使用code到可以简明地在控制器从每个HTML视图注入每个视图,然后直接调用一个服务而不会弄乱了冗余code中的控制器。

An AngularJS app needs to re-use multiple custom objects. I am concerned about creating cluttered, redundant code that is hard to maintain, so I moved re-usable code to a service that can be concisely injected in the controller for each view and then called directly from each html view without cluttering the controllers with redundant code.

下图说明了如何服务 someclass.js 将被重新使用,因此为什么尽可能多的code尽可能的隔离是很重要的在一个地方:

The following image illustrates how the service someclass.js will be re-used, and thus why it is important to isolate as much of its code as possible in one place:

我已经开发了code这部分完成这个对我devbox,我已经贴code到plnkr 。 (谢谢@shakir获得此plnkr重现问题)。我还包括以下code。

I have developed code that partially accomplishes this on my devbox, and I have posted the code to a plnkr. (Thank you to @shakir for getting this plnkr to recreate the problem.) I am also including the code below.

虽然点击表单提交按钮不会导致服务形式的处理方法被调用,问题是应该包含表单的数据对象在someclass.method1()方法是未定义应该处理表单的数据。 需要什么具体的改变code至作出以下,从而能够从形式向用户提交的数据的价值可以在服务的表单处理方法中被操纵?

Though clicking a form submit button does cause the form's handler method in the service to be called, the problem is that the object that should contain the form's data is undefined in the someclass.method1() method that should handle the form's data. What specific changes need to be made to the code below so that the value of the user-submitted data from the form can be manipulated inside the service's form handling method?

的视图和服务(通过控制器)之间的通信完整的要求是:

1。) someclass.prop1 可以有它的价值在视图中印(这部作品在低于code)和

1.) someclass.prop1 can have its value printed in the view (this works in the code below), and

2)。在 NG-提交 confirmForm 中可以直接调用 someclass.method1 作为一个处理程序,从而尽量减少 someroute.js 的code(这种情况在code以下,但没有定义应包含表单的数据对象时 someclass.somemethod1()运行)

2.) the ng-submit of confirmForm can directly call someclass.method1 as a handler and thus minimize the code in someroute.js (this happens in the code below, but the object that should contain the form's data is not defined when someclass.somemethod1() is running)

plnkr code:

下面是的plnkr 与呼叫通过 @JoaozitoPolo建议服务。目前的版本是能够调用 someclass.method1()从视图,但表单数据不传递给函数。因此,我们需要弄清楚如何将表单数据传递到功能。

Here is the plnkr with the call to the service suggested by @JoaozitoPolo. The current version is able to call the someclass.method1() from the view, but the form data is not passed into the function. So we need to figure out how to pass the form data into the function.

code中所示这边也:

在code,它(在我devbox)与 someclass.js someview.html 的连接方法$ C>(但不函数调用时从表单中的数据发送到 someclass.js )包含如下如下:

The code that (on my devbox) connects the properties and methods of someview.html with someclass.js (but does not send the data from the form into someclass.js during the function call) is included as follows below:

下面是code为 someclass.js

angular
.module('someclass', ['ngCookies'])
.service('someclass', ['$rootScope', '$http', '$cookies', function($rootScope, $http, $cookies){

this.prop1 = $cookies.get('test1');
this.prop2 = 'nothing';
this.resultphone = {};

this.method1 = function(isValid, resultphone) {
    if(isValid){
        var funcJSON = resultphone;
        funcJSON.wleadid = '1';//resultphone is undefined in debugger here
        alert("just a filler to add breakpoint for debugger");
        $http.post('/some-test-service', funcJSON).then(
            function(response) {
                prop2 = response.data.content;
            }
        );
    }
};

}]);

下面是code为 someroute.js

angular
.module('someroute', ['someclass'])
.controller('someroute', function($scope, someclass) {

    $scope.someclass = someclass;

});

下面是 someroute.html

someclass.prop1 is: {{someclass.prop1}} <br>
someclass.prop2 is: {{someclass.prop2}} <br>
<div ng-show="someclass.prop1!='yes'">
    <h1>someclass prop1!</h1>
    <div ng-include="'someroute_start.html'"></div>
</div>
<div ng-show="someclass.prop1=='yes'">

    <div ng-show="someclass.prop2=='showfirst'">
        <h1>Include start.</h1>
        <div ng-include="'someroute_first.html'"></div>
    </div>

    <div ng-show="someclass.prop2=='showsecond'">
        <h2>Include second.</h2>
        <div ng-include="'someroute_second.html'"></div>
    </div>

</div>

下面是 someroute_start.html ,其中包括需要由 someclass.js 处理形式:

Here is someroute_start.html, which includes the form that needs to be handled by someclass.js:

    <form name="confirmForm" ng-submit="someclass.method1(confirmForm.$valid)" novalidate>
        Enter some value: 
        <input type="text" name="phonenum1" ng-model="resultphone.phonenum1" required />
        <button type="submit" ng-disabled="confirmForm.$invalid" >Submit</button>
    </form>

有关完整性,我包括 someroute_first.html ,这很简单,只要:

For completeness, I am including someroute_first.html, which is as simple as:

<h3>Showing first! </h3>

someroute_second.html ,这很简单,只要:

<h3>Showing second! </h3>

该应用的主控制器 hello.js ,这我包括在解决方案的情况下,一部分这里包括初始化 SomeClass的

The main controller for the app is hello.js, which I am including here in case part of the solution includes initializing someclass:

angular
    .module('hello', [ 'ngRoute', 'someclass', 'home', 'someroute', 'navigation' ])
    .config(

            function($routeProvider, $httpProvider, $locationProvider) {

                $locationProvider.html5Mode(true);

                $routeProvider.when('/', {
                    templateUrl : 'home.html',
                    controller : 'home'
                })
                .when('/someroute', {
                    templateUrl : 'someroute.html',
                    controller : 'someroute'
                }).otherwise('/');

                $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

            }
    )

有关completelness, index.html的加载模块如下:

For completelness, index.html loads the modules as follows:

<!DOCTYPE html>
<html>
  <head>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />

    <link href="style.css" rel="stylesheet"/>
    <style type="text/css">
    [ng\:cloak], [ng-cloak], .ng-cloak { display: none !important; }
    </style>
  </head>

  <body class="ng-cloak" ng-cloak="" ng-app="hello">
    <div class="container" ng-controller="navigation">
      <ul role="tablist" class="nav nav-pills">
        <li ng-class="{active:tab('home')}">
          <a href="#/">home</a>
        </li>
        <li ng-class="{active:tab('someroute')}">
          <a href="#/someroute">some route</a>
        </li>
      </ul>
    </div>
    <div class="container" ng-view=""></div>

    <script type="text/javascript" src="someclass.js"></script>
    <script type="text/javascript" src="home.js"></script>
    <script type="text/javascript" src="someroute.js"></script>
    <script type="text/javascript" src="navigation.js"></script>
    <script type="text/javascript" src="hello.js"></script>
  </body>
</html>

此外,以上所有code都包含在需要code的最低限度的摘录在这个plnkr 重现该问题。 所以需要作出比1),得到plnkr工作,2)获取表单数据传递到调用 someclass.method1()有什么具体的变化

Again, all of the above code is included in a bare minimum excerpt of code required to reproduce the problem at this plnkr. So what specific changes need to be made to 1.) get the plnkr to work and 2.) get the form data to be passed into the call to someclass.method1()?

推荐答案

我看看你的plunker更新。优秀的。

I look your plunker updated. Excellent.

仅在someclass.js一个问题......你需要用$这个在内部函数变量来访问正确的范围:

Only an issue on someclass.js... you need to use "$this" variable at internal functions to access the correct scope:

$http.post('/some-test-service', funcJSON).then(
    function(response) {
        $this.prop2 = response.data.content;
    }
);

这篇关于为什么不能AngularJS视图发送数据到这个可重用的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆