【问题标题】:AngularJS: input cleaning doesn't work in stateAngularJS:输入清理在状态下不起作用
【发布时间】:2016-08-22 08:26:06
【问题描述】:

我遇到了一些问题。我编写了通过单击按钮清除输入的函数,但是当我使用 $stateProvider 并且在 state 中实现了清理时它不起作用。

app.js:

    <script>
    var app = angular.module("app", ['ui.router']); 
    app.config(function($stateProvider, $urlRouterProvider){

        $urlRouterProvider.otherwise("/first");

        $stateProvider
        .state("first", {
            url: "/first",
            templateUrl: "first.html"
        })
        .state("second", {
            url: "/second",
            templateUrl: "second.html"
        });

    });

    app.controller("ctrl", function($scope){

        $scope.searchAll = "";

        $scope.clearSearch = function () {
            $scope.searchAll = "";
        };
    });
</script>

页面:

<body ng-controller = "ctrl">
<div class = "container" >

    <button type="button" class="btn btn-success"><a ng-href="#/first">First</a></button>
    <button type="button" class="btn btn-success"><a ng-href="#/second">Second</a></button>
    <br>
    <ui-view><ui-view>
</div>
</body>

先声明:

FIRST SIDE!!!!!
<input type="text" class="form-control" ng-model="searchAll"></input> 
<a  href=""  data-ng-click="clearSearch()">X</a>

状态秒:

SECOND SIDE!!!!

【问题讨论】:

  • 你为什么要这样做???这么简单,你为什么要在 state 中使用它?
  • 我需要在不刷新的情况下更改页面,并且其中一个页面包含必须通过按钮清理的输入。它很简单,但不起作用。

标签: javascript angularjs input angular-ngmodel


【解决方案1】:

我不是 100% 从您的描述中确定,但猜测您的状态模板中的属性不会绑定到您的控制器的 $scope,因为它们在您的整页控制器被实例化时不存在.

所以,有几件事:

您最好为每个 ui 视图使用单独的控制器,而不是为整个页面使用单个控制器,这样当您移动到该状态时,控制器将绑定到单独的状态模板。

$stateProvider
    .state("first", {
        url: "/first",
        templateUrl: "first.html",
        controller: 'FirstCtrl as first'
    })

除非你添加一个 e.preventDefault();对于点击事件,使用 span 或 div 标签更容易。

对每个状态的链接使用 ui-srefs 而不是 ng-href,例如。

<a ui-sref="first">First</a>

最后,现在是停止使用 $scope 的好时机,因为它在 Angular 2 中消失了,并且不再是 Angular 1.* 应用程序中的最佳实践 - 改为使用控制器作为语法 - https://toddmotto.com/digging-into-angulars-controller-as-syntax/

https://plnkr.co/edit/3yStlPEozNGM886nEoXg?p=preview 上查看您的代码进行上述更改 - 清除按钮按预期工作

【讨论】:

  • 好的。非常感谢,但是两个控制器给了我另一个问题。如何在这两个控制器之间传输变量?我应该使用 localStorage 还是其他东西?
  • 最好的方法是提供服务,对于这个小例子来说可能有点矫枉过正,但这是最好的规模 - 将其添加到 plunkr,但直到明天才有时间对不起。
  • 我向 plunkr 添加了一项基本服务,以展示如何使用它在控制器之间共享数据。您应该尝试让控制器专注于单个视图,并将可重用的逻辑和数据移动到服务中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2011-04-03
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 2014-07-15
相关资源
最近更新 更多