2015-10-14 34 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

相關問題