Angular js自定义指令和2路数据绑定问题

时间:2015-12-02 18:52:35

标签: javascript html angularjs

我正在尝试使用角度js中的自定义指令实现下面的用例。

公司表格,其中包含3组不同的地址信息。

  1. 公司地址
  2. 范围地址
  3. 分部地址
  4. 需要定义可以重复使用的自定义地址指令。 一旦用户指定了所需信息,封装3组地址的Company对象将通过Web服务调用持久保存到后端数据存储。

    相关代码文件上传到plunker:http://plnkr.co/edit/H8Cmlf?p=info

    地址指令:

    angular.module('address.module')
      .directive('qiAddress', function() {
        return {
          restrict: 'E',
          scope: {
            qiAddressInfo: '=instance'
          },
          templateUrl: 'address.html'
        };
      });
    

    地址控制器:

    angular.module('address.module')
        .controller('address.controller', AddressController);
    AddressController.$inject = ['AddressService'];
    function AddressController(AddressService){
        var vm = this;
        //vm.qiAddressInfo = AddressService.newAddress();
        vm.cities = AddressService.getCities();
        vm.states = AddressService.getStates();
        vm.countries = AddressService.getCountries();
        vm.postalCodes = AddressService.getPostalCodes();
    
    }
    

    地址服务:

    /**
     * 
     */
    angular.module('address.module')
        .factory('AddressService', AddressService);
    function AddressService($http){
    
            var cities = [];
            var states = [];
            var countries = [];
            var postalCodes = [];
            function Address(){
                this.name = null;
                this.street = null;
                this.city = null;
                this.state = null;
                this.country = null;
                this.postalCode = null;
            };
    
    
            //declare functions for closure
            var service = {
                    //Address Object
                    newAddress : newAddress,
    
                    //Values to populate various drop downs
                    getCities : getCities,
                    getStates : getStates,
                    getCountries : getCountries,
                    getPostalCodes : getPostalCodes,
    
    
            };
            return service;
    
            //function definitions
            function newAddress(){
                return new Address();
            }
    
            function getCities(){
                //TODO - Get the list of cities from back end vi a web service call
                if (cities === null || cities.length === 0){
                    cities = ["Bangalore",
                              "Mumbai",
                              "Chennai",
                              "Hyderabad",
                              "Delhi",
                              "Calcutta"
                              ];
    
                }
                console.log(cities);
                return cities;
            }
    
            function getStates(){
                //TODO - Get the list of states from back end vi a web service call
                if (states === null || states.length === 0){
                    states = ["Karnataka",
                              "Maharashtra",
                              "Tamil Nadu",
                              "Andhra Pradesh",
                              "Delhi",
                              "West Bengal"
                              ];
    
                }
                return states;
            }
    
            function getCountries(){
                //TODO - Get the list of countries from back end vi a web service call
                if (countries === null || countries.length === 0){
                    countries = ["India"];
    
                }
                return countries;
            }
    
            function getPostalCodes(){
                //TODO - Get the list of postal codes from back end vi a web service call
                if (postalCodes === null || postalCodes.length === 0){
                    postalCodes = ['560079',
                                   '560078',
                                   '560077'
                              ];
    
                }
                return postalCodes;
            }
    
    
    };
    

    Address.html:

    <div ng-controller="address.controller as vm">
    
      <!-- <div id="addressContainer" class="container">  -->
        <div class="form-group">
            <label for="address.name" class="col-sm-2 control-label">Name</label>
            <div class="col-sm-4">
                <input class="form-control input-sm" id="address.name" ng-model="vm.qiAddressInfo.name"
                    placeholder="Enter Name"/>
            </div>
        </div>
        <div class="form-group">
            <label for="address.street" class="col-sm-2 control-label">Street</label>
            <div class="col-sm-4">
                <input class="form-control input-sm" id="address.street" ng-model="vm.qiAddressInfo.street"
                    placeholder="Enter Street"/>
            </div>
        </div>
        <div class="form-group">
            <label for="address.city" class="col-sm-2 control-label">City</label>
            <select name="address.city" id="address.city" ng-model="vm.qiAddressInfo.city">
                <option ng-repeat="city in vm.cities" value="{{city}}">{{city}}</option>
            </select>
        </div>
        <div class="form-group">
            <label for="address.state" class="col-sm-2 control-label">State</label>
            <select name="address.state" id="address.state" ng-model="vm.qiAddressInfo.state">
                <option ng-repeat="state in vm.states" value="{{state}}">{{state}}</option>
            </select>
        </div>
        <div class="form-group">
            <label for="address.country" class="col-sm-2 control-label">Country</label>
            <select name="address.country" id="address.country" ng-model="vm.qiAddressInfo.country">
                <option ng-repeat="country in vm.countries" value="{{country}}">{{country}}</option>
            </select>
        </div>
        <div class="form-group">
            <label for="address.postalCode" class="col-sm-2 control-label">Postal
                Code</label>
            <select name="address.postalCode" id="address.postalCode" ng-model="vm.qiAddressInfo.postalCode">
                <option ng-repeat="postalCode in vm.postalCodes" value="{{postalCode}}">{{postalCode}}</option>
            </select>
        </div>
    
    </div>
    

    company-detail.html :(相关部分包含在下方。有关完整文件,请参阅plunker) ....                                           公司地址                                                                                               

                <!--  Range Address -->
               <div class="panel panel-primary">
                   <div class="panel-heading">Range Address</div>
                        <div class="panel-body">
                            <qi-address instance="vm.company.rangeAddress"></qi-address>
                        </div>
               </div>
    
                <!-- Division Address -->
               <div class="panel panel-default">
                   <div class="panel-heading">Division Address</div>
                        <div class="panel-body">
                            <qi-address instance="vm.company.divisionAddress" ng-model="vm.company.divisionAddress"></qi-address>
                        </div>
               </div>
    

    公司控制器

    /**
     * 
     */
    angular.module('company.detail.module', ['address.module'])
            .config(['$httpProvider', function($httpProvider) {
                $httpProvider.defaults.useXDomain = true;
                delete $httpProvider.defaults.headers.common['X-Requested-With'];}])
            .controller('company.detail.controller', CompanyDetailController);
    
    CompanyDetailController.$inject = ['$scope', '$http','AddressService'];
    function CompanyDetailController($scope, $http, AddressService){
        var vm = this;
    
        /* - should we specify these here for placeholder text.. not sure..
        vm.companyCode = 'Enter Company Code';
        vm.companyName = 'Enter Company Name';
        vm.companyPhone = 'Enter Phone';
        vm.companyFax = 'Enter Fax';
        vm.companyECCNumber = 'Enter ECC Number';
        vm.companyTIN = 'Enter TIN';
        vm.companyTINDate = 'Select TIN Date';
        vm.companyCSTNumber = 'Enter CST Number';
        vm.companyCSTDate = 'Select CST Date';*/
    
        vm.cities = AddressService.getCities();
        vm.states = AddressService.getStates();
        vm.countries = AddressService.getCountries();
        vm.postalCodes = AddressService.getPostalCodes();
    
        vm.company = {};
        vm.company.companyCode;
        vm.company.companyNm;
        vm.company.companyPhone;
        vm.company.companyFax;
        vm.company.companyEccNbr;
        vm.company.companyTinNbr;
        vm.companyTinDt;
        vm.company.companyCst;
        vm.company.companyCstDt;
    
    
        /*
         * Address objects - Instantiate new address objects.
         * The content of this will(should) be set via the directive qi-address-info
         */
        vm.company.companyAddress = AddressService.newAddress();
        vm.company.rangeAddress = AddressService.newAddress();
        vm.company.divisionAddress = AddressService.newAddress();
    
        //TODO - Move this function to Company Service/Factory
        vm.createCompany = function(company) {
            console.log("JSON REQUEST for creating company: " +angular.toJson(company, true));
            $http({
              method: 'POST',
              url: 'something appropriate',
              data    : vm.company
            }).then(function(response) {
                // this callback will be called asynchronously
                // when the response is available
                console.log("Create: Response returned form web service: " +response);
              }, function (response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                  console.log("Error from web service for Create. Response: " +response);
              });
    
        };
    
      };
    

    公司明细模块:

    /**
     * 
     */
    
    var app = angular.module('company.detail.module', ['address.module']);
    

    我面临的问题:

      

    指令HTML中指定的信息未绑定到父公司对象。

    我观察到的内容:当我通过Chrome(batarang)进行调试时,最里面范围内的模型具有用户键入的值(如预期的那样),但是父级中的Company对象scope具有Address属性的空值。

    我是一个ng-noob和一个js-noob。

    我很感激任何建议和方向

1 个答案:

答案 0 :(得分:2)

这是一个有效的plunker。变化如下:

  • 删除了addressController.js,因为它没有正确使用,不需要作为单独的文件,也删除了对它的引用
  • 在地址指令中引入了新的指令控制器,并调整了html模板以对应
  • 添加pre标记以在父控制器范围上打印您的模型,以查看值是否正确更改。

如果您有任何其他问题,请不要犹豫问我。