如何从其他View清除一个View的输入值?

时间:2015-09-02 09:23:19

标签: javascript jquery html asp.net angularjs

我的情景非常简单直接。但是我没有得到确切的输出。

就我而言,我有两个名为index.htm,Main.htm的html页面和一个名为mscript.js的脚本页面。 Index.htm由一个按钮(Clear)和Main.htm组成,其中一个输入类型字段为文本。

我想要的是:

单击按钮(从索引视图),用户在输入类型字段(从主视图中)输入的文本必须被清除。

我尝试的是

我使用了配置块。

INDEX.HTM:

<div data-ng-app="mangular">
    <div data-ng-controller="mcontroller">Strictly for Demo Purpose
        <br />
        <br />
        <br />
        <div data-ng-view=""></div>
        <br />
        <button type="submit" data-ng-click="clear()">Clear</button>
    </div>
</div>

main.htm中

<div>
  Type your Name : 
  <input type = "text" data-ng-model = "demotext" />
</div>

mscript.js

 var mangular = angular.module('mangular', ['ngRoute']);

mangular.config(function ($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'Main.htm'
    })
});

mangular.controller('mcontroller', function ($scope) {

    //var test = mfactory.getinput();
    $scope.clear = function () {
        $scope.demotext = ""; // This is the place where I'm expecting solution
    }
});

3 个答案:

答案 0 :(得分:1)

使用$broadcast,angularjs的内置服务。在第一页按钮上单击广播,然后在第二页中接收广播事件并清除输入元素上的数据。

来自mcontroller

$rootScope.$broadcast("cleardata", anyObject);  // here you are broadcasting some data which is identified the a name/key that is for this example 'cleardata'
Main.htm

的控制器中

$rootScope.$on("cleardata", function (event, objectData) {
    // do whatever you want and clear the textbox
});

答案 1 :(得分:1)

试试这个:http://jsfiddle.net/sherali/Mh2UH/31/

但是, - 我将控制器添加到`$ routeProvider。

  • 在里面,我添加了$scope.$watch

然后它起作用

var myApp = angular
    .module('myApp', ['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                template: '<div>Type your Name : <input type = "text" ng-model = "text" /></div>',
                controller: 'viewCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    })

...

myApp.factory('aProvider', function () {
    return {
        text: "default Text"
    }
});

...

myApp.controller('myCtrl', function ($scope, aProvider) {
    $scope.clear = function () {
        aProvider.text = "";
    }
});

myApp.controller('viewCtrl', function ($scope, aProvider) {
    $scope.$watch(function () {
        return aProvider.text;
    }, function (val) {
        $scope.text = val;
    })

    $scope.$watch('text', function (val) {
        aProvider.text = val;
    })
});

答案 2 :(得分:0)

为Main.html创建一个控制器,例如mainctrl,并从mcontroller创建一个控制器$scope.$parent.mainctrl.demotext = "";