AngularJS指令范围变量未定义

时间:2015-07-09 18:18:52

标签: javascript angularjs directive

这是相关的JSFiddle

https://jsfiddle.net/9Ltyru6a/3/

在小提琴中,我设置了一个控制器和一个指令,我想用它在值发生变化时调用回调。我知道Angular有一个ng-change指令,但我想要更类似于标准的onchange事件(当字段模糊时会触发一次)。

控制器:

var Controllers;
    (function (Controllers) {
    var MyCtrl = (function () {
        function MyCtrl($scope) {
            $scope.vm = this;
        }

        MyCtrl.prototype.callback = function (newValue) {
            alert(newValue);
        };

        return MyCtrl;
    })();
    Controllers.MyCtrl = MyCtrl;
})(Controllers || (Controllers = {}));

指令:

var Directives;
(function (Directives) {
    function OnChange() {
        var directive = {};
        directive.restrict = "A";
        directive.scope = {
            onchange: '&'
        };
        directive.link = function (scope, elm) {
            scope.$watch('onChange', function (nVal) {
                elm.val(nVal);
            });
            elm.bind('blur', function () {
                var currentValue = elm.val();
                scope.$apply(function () {
                    scope.onchange({ newValue: currentValue });
                });
            });
        };
        return directive;
    }
    Directives.OnChange = OnChange;
})(Directives || (Directives = {}));

HTML:

<body ng-app="app" style="overflow: hidden;">
    <div ng-controller="MyCtrl">
        <button ng-click="vm.callback('Works')">Test</button>
        <input onchange="vm.callback(newValue)"></input>
    </div>
</body>

按钮有效,所以我可以安全地说(我认为)控制器很好。但是,每当我更改输入字段的值并且不聚焦时,我得到一个&#34; vm未定义&#34;错误。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

首先,使用适当的控制器作为符号,而不是$scope.vm = this;

ng-controller="MyCtrl as vm"

然后不要将自定义指令与本机onchange事件处理程序混合使用 - 这就是导致undefined错误的原因。将您的指令命名为onChange,并改为使用on-change属性。

正确的代码如下:

var app = angular.module("app", []);

var Directives;
(function (Directives) {
    function OnChange() {
        var directive = {};
        directive.restrict = "A";
        directive.scope = {
            onChange: '&'
        };
        directive.link = function (scope, elm) {
            elm.bind('blur', function () {
                var currentValue = elm.val();
                scope.$apply(function () {
                    scope.onChange({
                        newValue: currentValue
                    });
                });
            });
        };
        return directive;
    }
    Directives.onChange = OnChange;
})(Directives || (Directives = {}));

app.directive("onChange", Directives.onChange);


var Controllers;
(function (Controllers) {
    var MyCtrl = (function () {
        function MyCtrl($scope) {

        }

        MyCtrl.prototype.callback = function (newValue) {
            alert(newValue);
        };

        return MyCtrl;
    })();
    Controllers.MyCtrl = MyCtrl;
})(Controllers || (Controllers = {}));

app.controller("MyCtrl", ["$scope", function ($scope) {
    return new Controllers.MyCtrl($scope);
}]);

演示: https://jsfiddle.net/9Ltyru6a/5/

答案 1 :(得分:1)

如果您的代码的目的是仅更新模糊的控制器值,而不是在每次按键时更新它,则角度为String s = String.join(",", Collections.nCopies(5, "?")); 用于此用途。例如:

ngModelOptions

你甚至可以提供去抖动,或者按钮来清除价值......

<input type="text" ng-model="user.name" ng-model-options="{ updateOn: 'blur' }" />

在这些情况下,如果您要提供<form name="userForm"> <input type="text" name="userName" ng-model="user.name" ng-model-options="{ debounce: 1000 }" /> <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button> </form> ,则只会在模糊事件或去抖后触发。

您还可以编写直接利用ng-change

中的$validators$asyncValidators的指令

这是Angular Developer Guide的一个例子:

ngModelController

和HTML:

app.directive('username', function($q, $timeout) {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
    var usernames = ['Jim', 'John', 'Jill', 'Jackie'];

      ctrl.$asyncValidators.username = function(modelValue, viewValue) {

        if (ctrl.$isEmpty(modelValue)) {
          // consider empty model valid
          return $q.when();
        }

        var def = $q.defer();

        $timeout(function() {
          // Mock a delayed response
          if (usernames.indexOf(modelValue) === -1) {
            // The username is available
            def.resolve();
          } else {
            def.reject();
          }

        }, 2000);

        return def.promise;
      };
    }
  };
});

您当然可以添加<div> Username: <input type="text" ng-model="name" name="name" username />{{name}}<br /> <span ng-show="form.name.$pending.username">Checking if this name is available...</span> <span ng-show="form.name.$error.username">This username is already taken!</span> </div> 以确保只触发一次。