2015-10-14 69 views
1

我需要创建自定义指令

<my-input id="myInputElementId1" 
      label="My Label 1" 
      ng-model="myInputElementModel1" 
      ng-change="resetFormFieldErrors(form.myInputElementId1)" 
      ng-required="true"></my-input> 

它应该像下面里面工作代码如下:

"use strict"; 

module.exports = 
    function myInput() { 
     return { 
      require: "ngModel", 
      scope: { 
       model: "=ngModel", 
       id: "@", 
       label: "@", 
       required: "@?" 
      }, 
      link: function (scope, element, attrs) { 
       scope.$watch("model", function (newValue, oldValue) { 
        if (newValue != oldValue) { 
         if (attrs.ngChange) { 
          console.log("Should execute: " + attrs.ngChange); 
          scope.$eval(attrs.ngChange); 
         } 
        } 
       }); 
      }, 
      templateUrl: "app/campaign/templates/search/myInput.html" 
     }; 
    }; 

m yInput.html代码如下:那新指令使用的

<div> 
    <label for="{{id}}"><span>{{label}}</span></label> 
    <input id="{{id}}" name="{{id}}" type="text" ng-model="model" ng-required="required"/> 
</div> 

实施例是如下:

<my-input id="myInputElement1" 
      label="My Label 1" ng-model="myInputElement1" 
      ng-change="resetFormFieldErrors(form.myInputElement1)"></my-input> 

<my-input id="myInputElement2" 
      label="My Label 2" 
      ng-model="myInputElement2" ng-change="resetFormFieldErrors(form.myInputElement2)"></my-input> 

<my-input id="myInputElement3" 
      label="My Label 3" 
      ng-model="myInputElement3" ng-change="resetFormFieldErrors(form.myInputElement3)"></my-input> 

当我改变输入元件的文本的console.log每次(“应该执行:“+ attrs.ngChange)工作正常,但范围。$ eval(attrs.ngChange)不起作用,并且不存在执行错误。

有人请帮助我。

回答

2

我相信你会需要调用$eval父范围,所以像scope.$parent.$eval();

这是必要的,因为在你的指令中scope创建一个孤立的范围,但attrs.ngChange被引用父范围。

+0

感谢与方法变NG-变化!有用! – J2James

0

不知道究竟你打算使用范围。$ EVAL,反而我会建议你通过以下方式这将是做最适当的方式根据您的上述要求。

module.exports = 
    function myInput() { 
     return { 
      require: "ngModel", 
      scope: { 
       model: "=ngModel", 
       id: "@", 
       label: "@", 
       required: "@?", 
       methodChange: '&?' 
      } 
      controller: ['$scope', function($scope) { 
       $scope.$watch('model', function (newValue, oldValue) { 
        if (newValue != oldValue) { 
        if ($scope.methodChange) { 
         $scope.methodChange(); 
        } 
        } 
       }); 
      }] 
      }, 
      templateUrl: "app/campaign/templates/search/myInput.html" 
     }; 
    }; 

并替换指令模板

+0

methodChange不是这种情况。 ng-change可以包含任何有效的代码(不仅是函数调用w \ o参数)。 – J2James

相关问题