0

我有了這個代碼(更新)傳遞一種形式的指令:未定義

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

+1

'return scope.form [scope.toWatch]。$ error;'產生錯誤 – Ronnie

+0

我解決了它:我更新了plunk以反映問題。如果您將element.append(inputDiv)函數調用移入transclude函數,它會以某種方式開始工作。 – raichu

回答

1

我看到兩件事情是可以改變的,首先我要補充一個ng-model屬性的文本輸入和ng-required屬性,這樣的錯誤將與模型的控制器來追蹤

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

下次你需要包括在$腕錶objectEquality參數,所以它會監視在$錯誤對象屬性

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

+0

哦,所以沒有ng-model,表單保持不確定狀態?但我在我的真實應用程序中有一個ng模型。 – raichu

+0

如果沒有ng模型,您將不會在輸入中獲得內置角度錯誤檢查,因爲輸入不會有模型控制器。 –

相關問題