繁体   English   中英

AngularJS自定义指令两种方式绑定不起作用

[英]Angularjs custom directive two way binding not working

我创建自定义指令并使用两种方式绑定(=)

但是我想观察模型在指令中更改时控制器中的更改。

<div ng-app="zippyModule">
  <div ng-controller="Ctrl3">
    Title: <input ng-model="title">
    <hr>
    <div class="zippy" zippy-title="title" ff="titleChanged()"></div>
  </div>
</div>


function Ctrl3($scope) {
  $scope.title = 'Lorem Ipsum';
    $scope.titleChanged = function() {
        //ALERT COMMING WITH OLD VALUE NOT UPDATED
         alert($scope.title);
    }
}

angular.module('zippyModule', [])
  .directive('zippy', function(){
    return {
      restrict: 'C',
      replace: true,
        scope: { title:'=zippyTitle',f:'&ff' },
      template: '<input type="text" value="{{title}}"style="width: 90%" ng-click="onclick()"/>',
      link: function(scope, element, attrs) {
        // Your controller
          scope.onclick = function() {
               scope.title +="_";
              if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {
                    scope.$apply();
              }
              scope.f();

          }
      }
    }
  });

titleChanged方法正在调用,但是$ scope.title带有旧值。 如果我删除

if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {

如果if并调用direcly scope。$ apply()方法,

正在应用进行中异常抛出。

正如@Omri所说,您应该将模型值放在作用域内的对象内,而不是直接在作用域上具有字符串。

但是,您可能只想使用ng-model来处理跟踪模型更改:

  angular.module('zippyModule', [])
      .controller('Ctrl3', function($scope) {
      $scope.model = {title : 'Lorem Ipsum'};
        $scope.titleChanged = function() {
            //ALERT COMMING WITH OLD VALUE NOT UPDATED
             alert($scope.model.title);
        }
      })
      .directive('zippy', function(){
        return {
          restrict: 'C',
          replace: true,
            scope: {f:'&ff' },
            require: 'ngModel',
          template: '<input type="text" style="width: 90%" ng-click="onclick()"/>',
          link: function(scope, element, attrs, ctrl) {
            // Use ngModelController
              ctrl.$render = function() {
                element.val(ctrl.$modelValue);
              };
              scope.onclick = function() {
                var newVal = ctrl.$modelValue + '_';
                element.val(newVal);
                ctrl.$setViewValue(newVal);
                scope.f();
              }
          }
        }
      });

然后更新您的HTML以使用ng-model:

    <div ng-app="zippyModule">
      <div ng-controller="Ctrl3">
        Title: <input ng-model="model.title">
        <hr>
        <div class="zippy" zippy-title ng-model="model.title" ff="titleChanged()">
        </div>
      </div>
    </div>

小提琴: https : //jsfiddle.net/sLx9do3c/

查看ngModelController的文档,了解您最终可能需要的所有其他功能。 https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

暂无
暂无

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

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