[英]Scope object is undefined in Angular directive
我正在嘗試理解這種行為,並添加了我正在嘗試執行的簡化代碼。 在使用模式控制器的模式的HTML部分中,我有一些類似以下的代碼:
<form>
<!-- example one -->
<div read-field="{{ singleContact._id }}" ></div>
<h2>{{ singeContact._id }}</h2>
<!-- example two -->
<div read-field="{{ someScope }}"></div>
</form>
和指令:
angular.module('myApp')
.directive('readField', function () {
return {
link: function (scope, element, attrs) {
console.log(attrs); // outputs correct object with attrs.readField "523c2..mongo_id.."
console.log(attrs.readField); // outputs and empty string
}
};
});
即使singleContact._id值正確顯示在h2的頁面上,並正確顯示在僅記錄(attrs)返回的對象中,但記錄變量attrs.readField會直接返回一個空字符串。 在第二個示例中使用someScope做同樣的事情,一切工作正常,即attrs.someScope的console.log返回“ Foo”。
顯然,這是如何在控制器中進行設置的問題:示例一(singleContact)來自對api服務的函數調用,示例二(someScope)是直接聲明。
angular.module('myApp')
.controller('EditModalCtrl', function ($scope, $modalInstance, $rootScope, apiCalls, id) {
apiCalls.getContact(id)
.success(function (data) {
console.log(data);
$scope.singleContact = data;
});
$scope.someScope = 'Foo';
});
非常感謝您使我理解這一點,我是新來的有經驗的人,並且感覺到我在這里錯過了一些重要的東西,謝謝。
singleContact._id在鏈接函數運行時未綁定到該屬性,因此將傳遞一個空字符串作為readField值。 請嘗試以下方法:
<form>
<div read-field="singleContact._id" ></div>
<h2>{{ singeContact._id }}</h2>
</form>
angular.module('myApp')
.directive('readField', function () {
return {
link: function (scope, element, attrs) {
console.log(attrs); // outputs correct object with attrs.readField "523c2..mongo_id.."
console.log(scope.$eval(attrs.readField)); // should evaluate the expression on the current scope
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.