为什么在添加解析器指令后输入未填充初始值

时间:2018-09-05 11:16:10

标签: angularjs angularjs-directive

我遇到了AngularJS 1.1.5的问题,在第一次加载输入时未填充初始值,这在1.2.x及更高版本中似乎还不错。我仅限此版本,因为它是Umbraco 7.9.2后端的解决方案。 这是将指令与$ parsers结合使用以基于控制器中定义的功能来验证输入的示例。 here on stack overflowhere广泛使用了类似的解决方案来避免手表。在这种情况下如何填充初始值?

html

<div ng-app="app">
   <div ng-controller="TitleWidget">
      <div class="help">
         <label id="TitleLabel" ng-model="model.value.combinedtitle">{{model.value.combinedtitle}}</label>
      </div>
      <input type="text" ng-model="model.value.title" myfunction="change" name="title" id="title"
        class="umb-editor umb-textstring textstring"
        val-server="value"
        ng-required="model.validation.mandatory"
        ng-trim="false"/>
      <span class="help-inline" val-msg-for="title" val-toggle-msg="valServer"></span>
      <span class="help-inline" val-msg-for="title" val-toggle-msg="required"><localize key="general_required">Required</localize></span>
      <div class="help" ng-if="model.maxlength">
         <strong>{{model.count}}</strong>
         <span>characters left</span>
      </div>
   </div>
</div>

和控制器

angular.module('app',[])
.controller('TitleWidget', function ($q, $scope, $rootScope, $http, 
$cacheFactory) {

$scope.init = function () {

        if (!$scope.model) {
            $scope.model = {};
        }

        if (!$scope.model.value) {
            $scope.model.value = {};
            $scope.model.value.combinedtitle = [];
            $scope.model.value.title = [];
        }
    };  

$scope.init();
$scope.model.value.title= "title";
$scope.model.value.combinedtitle= "combinedtitle";
$scope.model.count= 0;

$scope.change = function (value, text) {
     $scope.model.value.combinedtitle = value + " combined " + text;
     $scope.model.count= 100 - $scope.model.value.combinedtitle.length;
     return true;

    };

}).directive('myfunction', function () {
    return {

        scope: {
            myfunction: '&myfunction'
        },
        require: 'ngModel',
        link: function ($scope, element, attrs, ctrl) {

            ctrl.$parsers.push(function (view) {

                var result = $scope.myfunction()(view, "from directive");
                if (!result) {
                    ctrl.$setValidity('maxlen', false);

                } else {
                    ctrl.$setValidity('maxlen', true);
                }

                return view;
            });
        }
    };
}); 

jsfiddle演示问题here

0 个答案:

没有答案