在angularjs wetheen组件中编辑输入表单

时间:2018-10-20 18:10:27

标签: javascript angularjs

我正在尝试编辑表单whit angularjs。问题是我不能在shop.component和edit组件之间共享数据。 我执行ng-repeat来从服务中获取信息,然后当我单击shop组件中的edit buttom时,在edit组件上未定义。 这是我的代码。

shop.html

    <tbody class="table-hover">
         <tr ng-repeat="(id,local) in $ctrl.locals  | orderBy:sortType:sortReverse | filter: $ctrl.name | filter:$ctrl.address">
            <td>{{local.name}}</td>
            <td>{{local.address}}</td>
            <td>{{local.phone}}</td>
            <td>
                <button ng-click="$ctrl.editShop(id)" class="button expand success">Edit</button>
            </td>
        </tr> 
    </tbody>

shop.component

angular.module('app')
    .component('articleComponent', {
        bindings: {
            name: '<',
            address: '<'
        },
        templateUrl : 'app/articles/articles.html',
        controller : function(deliveryService, $location, $scope){

            this.locals = deliveryService.getDetailLocals() 

            this.sortType= 'name'; 
            this.sortReverse = true;

            this.editShop = function(id){
                $location.path("/edit/" + id) 
            }
        }
    })

edit.html

<form>
  <fieldset>
    <legend>{{ textButton }}</legend>

    <div class="row">
      <div class="large-12 columns">
        <label>name</label>
        <input type="text" placeholder="name" ng-model="local.name" required>
      </div>
    </div>

    <div class="row">
      <div class="large-4 columns">
        <label>Adress</label>
        <input type="text" placeholder="Edad" ng-model="local.adress" required>
      </div>
    </div>
    <button type="submit" class="button large-12">{{ textButton }}</button>
  </fieldset>
</form>

edit.component.js

angular
.module('app')
.component('editComponent', {
    bindings: {},
    templateUrl: 'app/edit/edit.html',
    controller: function ($scope, $routeParams) {
        $scope.textButton = "Edit user";
        console.log($scope.local) // --> undefined
        console.log($routeParams) // --> {id:'0'}
    }
})

service.js

angular.module('app')
.service('deliveryService', function(){
    this.getDetailLocals = function () {
        return [
            {name: 'Bar BQ', address: 'St. 12 nro 1587', phone:'456 715 42'},
            {name: 'XXX Bar', address: 'St. 44 nro 1548', phone:'156 715 42'}
        ]
    }
})

我知道如果我在ng-click函数中发送“ local”来发送整个对象,那么我会丢失ng-repeat生成的ID号吗?

有什么帮助吗? 谢谢!! 皮尔

1 个答案:

答案 0 :(得分:0)

您可以随时使用deliveryService来获取值,可以像在getDetailLocals内部一样调用article-component方法。

controller: function ($scope, $routeParams, deliveryService) {
    $scope.textButton = "Edit user";
    var locals = deliveryService.getDetailLocals();
    var selectedItem = locals.filter(function(local) {
        return local.id == $routeParams.id
    })
    console.log(selectedItem && selectedItem[0])
}