我無法理解Angular指令。我想用一個簡單的屬性來擴展到更復雜的html,但是這個模板的某些部分可以通過參數來替換。Angular指令使用ng-blur和ng-focus
鑑於此代碼:
<form role="form" name="databaseForm">
<input type="text" name="connectionName"
ng-focus="databaseForm.connectionName.$focused = true;databaseForm.connectionName.$blurred = false;"
ng-blur="databaseForm.connectionName.$blurred = true;databaseForm.connectionName.$focused = false;"
>
</form>
我想用更簡潔的指令(如「模糊爲中心」)來寫:
<form role="form" name="databaseForm">
<input type="text" name="connectionName"
blurred-focused="'databaseForm.connectionName'"
>
</form>
因此,這意味着我可以很可以輕鬆地將其用於其他輸入:
<form role="form" name="databaseForm">
<input type="text" name="username"
blurred-focused="'databaseForm.username'"
>
</form>
預期的結果是,帶有此指令的輸入將具有基於用戶與輸入的交互,自動應用$ blur和$ focused屬性。
謝謝。
更新: 我結束了使用MMHunter的版本,其中範圍是不可分離的。我添加了一些邏輯來自動查找表單和字段對象,所以我不需要全部指定。
我的指令:
(function() {
"use strict";
angular
.module("app.shared.widgets")
.directive("blurredFocused", blurredFocused);
blurredFocused.$inject = ["_"];
/* @ngInject */
function blurredFocused(_) {
return {
restrict: "A",
priority: -1,
link: function(scope, element, attributes) {
element.on("blur", function() {
var formFieldName = element[0].form.name + "." + element[0].name;
var target = _.get(scope, formFieldName);
scope.$apply(function() {
target.$blurred = true;
target.$focused = false;
});
});
element.on("focus", function() {
var formFieldName = element[0].form.name + "." + element[0].name;
var target = _.get(scope, formFieldName);
scope.$apply(function() {
target.$blurred = false;
target.$focused = true;
});
});
}
};
}
})();
及其用法的例子:
<form role="form" name="databaseForm">
<input type="text" name="connectionName" blurred-focused>
</form>
我真的不明白你需要什麼。 Ng-focus和ng-blur是相反的指令,因爲blur =失去焦點。聚焦代碼在聚焦模糊模糊時啓動。閱讀關於它 - http://www.w3schools.com/angular/ng_ng-focus.asp,http://www.w3schools.com/angular/ng_ng-blur.asp –
我基本上希望濃縮我有的語法第一個例子變成更可重用的東西,而不必隨處複製和粘貼該邏輯。邏輯的作用與問題無關。我意識到模糊和焦點是相反的,但我希望使用單一語法提供$ blur和$ focused特性。 – Casey