javascript - 将表单传递给指令 : undefined

标签 javascript angularjs angularjs-directive angularjs-scope

我有这个代码(已更新)

HTML

<body ng-controller="MainCtrl">
    <form name="form" novalidate>
      <directive form="form.test" required
      ><input type="text" ng-model="text" name="test" required="true" /></directive>
      <button ng-click="click()">Click me</button>
    </form>
  </body>

Javascript

app.controller('MainCtrl', function($scope) {
  $scope.click = function(){
    console.log('click');
  }
});

app.directive('directive', function() {
  return {
    transclude: true,
    replace: true,
    scope: {
      form: '=',
    },
    template: '<div>',
    link: function(scope, element, attrs, ctrl, transcludeFn) {
      var inputDiv = angular.element('<div>')
      transcludeFn(scope, function(clone){
        inputDiv.append(clone);
      })
      element.append(inputDiv);
      scope.$watch(function(){
        return scope.form.$error;
      }, function(newValue){
          console.log('newValue', newValue);
      }, true)
    }
  }
});

每次我单击该按钮时,都会收到未定义表单的错误。 在这里试试:http://plnkr.co/edit/pl76wo4AJiGH0m7b5NQd?p=preview

最佳答案

我看到有两件事可以更改,首先我会向文本输入添加一个 ng-model 属性和一个 ng-required 属性,这样错误就会使用模型的 Controller 进行跟踪

<input type="text" ng-model="test" ng-required="true" />

接下来您需要在 $watch 上包含 objectEquality 参数,这样它将监视 $error 对象属性的更改

scope.$watch(function(scope) {
  return scope.form[scope.toWatch].$error;
}, function(newValue) {
  // newValue will be the $error object from the input
}, true); // notice the last true value here, that's the objectEquality parameter

这是更新的 plnkr:http://plnkr.co/edit/LnGhWgZF5ZbnqRUxh4gP?p=preview

关于javascript - 将表单传递给指令 : undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35049166/

相关文章:

javascript - 使用 jQuery 在悬停时将列表项向右碰撞

javascript - UI Router - 状态转换延迟(非常慢)

php - Angularjs 发布到 SQL 服务器

angularjs - 用于缓存 Angular 应用程序文件的 Nginx 配置

angularjs - 如何测试指令链接中的功能

javascript - ng-show/hide 延迟图像动画

javascript - 这个 "require"是什么东西?

javascript - Extjs 将 xml 文件属性加载到存储中

需要 Angularjs Ui 网格分组格式

Angular : how to restrict input type number to allow only even number with min and max limit as well as steps to increase