简体   繁体   English

输入框为空时angularJS $ scope。$ watch无法正常工作

[英]angularJS $scope.$watch not working when input box becomes empty

I just started with AngularJS and I'm trying to share data between two ng-controllers (both controllers are in the same ng-app module) using a factory. 我刚开始使用AngularJS,并且试图使用工厂在两个ng-controllers之间共享数据(两个控制器都在同一个ng-app模块中)。 Data(HTML input field) from controller1 seems to get shared with controller2 most of the times; 来自controller1的数据(HTML输入字段)似乎大多数时候都与controller2共享; but when I delete all contents of the input field, the $watch doesn't seem to work! 但是当我删除输入字段的所有内容时,$ watch似乎不起作用! I'm finding it a little hard to explain in words. 我发现很难用言语解释。 The screenshots below might help. 下面的屏幕截图可能会有所帮助。

在此处输入图片说明

在此处输入图片说明

Here's my code: 这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <% include ../partials/head %>
  </head>

  <body class="container" ng-app='myApp'>

    <div ng-controller="ctrl1">
        <input type="text" ng-model="firstName">
        <br>
        Input is : <strong>{{firstName}}</strong>
    </div>

    <div ng-controller="ctrl2">
        Input should also be here: {{firstName}}
    </div>


    <script>

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

        myApp.factory('Data', function () {
            var data = {
              FirstName: ''
            }

            return {
              getFirstName: function () {
                  return data.FirstName;
              },
              setFirstName: function (x) {
                  data.FirstName = x;
              }
            }
        });

        myApp.controller('ctrl1', function ($scope, Data) {
            $scope.firstName = ''

            $scope.$watch('firstName', function(newVal){
              if(newVal){Data.setFirstName(newVal);}
            });
        });

        myApp.controller('ctrl2', function ($scope, Data) {
            $scope.$watch(function(){return Data.getFirstName();}, function(newVal){
              if(newVal){$scope.firstName = newVal;}
            });
        });
    </script>

  </body>

  <footer>
        <% include ../partials/footer %>
  </footer>
</html>

There's also a jsfiddle I found for this code. 我为该代码找到了一个jsfiddle。 http://jsfiddle.net/5LL3U/2/ http://jsfiddle.net/5LL3U/2/

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

You need to check both newValue with oldValue for this.In case of empty newValue it is not calling your factory and will not set the value on the variable. 您需要为此同时检查newValue和oldValue。如果newValue为空,它不会调用您的工厂并且不会在变量上设置值。 :- :-

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


myApp.factory('Data', function(){
    var data =
        {
            FirstName: ''
        };

    return {
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
});

myApp.controller('FirstCtrl', function( $scope, Data ) {

    $scope.firstName = '';

    $scope.$watch('firstName', function (newValue,oldValue) {
        console.log(oldValue+"   "+newValue);
        if (newValue!=oldValue) Data.setFirstName(newValue);
    });
});

myApp.controller('SecondCtrl', function( $scope, Data ){

    $scope.$watch(function () { return Data.getFirstName(); }, function (newValue,oldValue) {
        if (newValue!=oldValue) $scope.firstName = newValue;
    });
});

Fiddle:- http://jsfiddle.net/1d1vL1hd/ 小提琴:-http: //jsfiddle.net/1d1vL1hd/

Your condition is wrong. 您的情况不对。 When empty, newValue is falsy and firstName doesn't get updated. 如果为空,则newValue为falsy,并且firstName不会更新。

function (newValue) {
    if (newValue) Data.setFirstName(newValue);
});

So you need to change or remove your condition. 因此,您需要更改或删除条件。

$scope.$watch('object', function(new, old){ }, true ); $ scope。$ watch('object',function(new,old){}, true );

The true here is for object equality...like this watch is triggered always on value change 真正的意义在于对象相等...就像这个手表总是在值改变时被触发

Also, to share data between controllers use a service not a factory. 另外,要在控制器之间共享数据,请使用服务而非工厂。

Try this: just remove checking if (newValue) from your code. 尝试以下操作:只需从代码中删除是否检查if (newValue)

demo here 在这里演示

just change this: 只需更改此:

<input type="text" ng-model="firstName" ng-trim="false">

http://jsfiddle.net/twt2nbpL/#&togetherjs=53GqpR44vP http://jsfiddle.net/twt2nbpL/#&togetherjs=53GqpR44vP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM