Like ng-enabled
,ng-src
,ng-class
有什麼東西可以使它適用於任何屬性(ng-x
)?如何讓「ng-」使用任何屬性?
例如,這是我的代碼:
<div ng-attrbuite1="a" ng-otherattribute="b"></div>
我想它設置:
<div attribute1="a_value" attribute2="b_value_in_scope">
在運行時我還不知道,這將是該屬性的名稱存在在HTML中。
Like ng-enabled
,ng-src
,ng-class
有什麼東西可以使它適用於任何屬性(ng-x
)?如何讓「ng-」使用任何屬性?
例如,這是我的代碼:
<div ng-attrbuite1="a" ng-otherattribute="b"></div>
我想它設置:
<div attribute1="a_value" attribute2="b_value_in_scope">
在運行時我還不知道,這將是該屬性的名稱存在在HTML中。
如果你的意思,你想有一個包羅萬象,其中有前綴的所有屬性說my
(你應該使用您自己的前綴)進行評估,然後設置爲它們各自所需的非前綴屬性:
我將不包括製造您可以找到的實際指令here
在您的指令的link
函數中,其中一個參數將爲$attrs。 $attrs
包含規範化(駝峯式)和非規範化屬性名稱,它們各自的評估值(如果使用表達式)以及一些輔助方法。
所以你可以簡單地遍歷$ attrs(或$ attrs。$ attr)鍵,過濾出你不應該使用的類似ng-model,ng-selected等等,得到評估值然後設置相應的未加前綴的對應部分。
Object.keys($attrs).filter(function(key){
//filter out keys like ngModel,ngSelect,$set etc
return /^my/.test(key);
}).forEach(function(key){
//$attrs.$attr contains the non-normalized
//versions of the attributes
//this example assumes you will prefix with `my`
//so remove `my-` to get the attribute name to set
var attrName = $attrs.$attr[key].replace("my-","");
//Use $parse() if you just want to use some scope's property name
//for example my-attribute="somePropertyName"
$attrs.$set(attrName,$parse($attrs[key])($scope));
//Use just $attrs[key] if you are using some expression
//for example my-attribute="{{somePropertyName}}"
$attrs.$set(attrName,$attrs[key]);
});
angular.module("test",[])
.controller("ctrl",function($scope){
$scope.someprop = "Some Value";
})
.directive("caAttr",function($parse){
return {
restrict : 'A',
link : function($scope, $element, $attrs) {
console.log($attrs);
Object.keys($attrs).filter(function(key){
return /^my/.test(key);
}).forEach(function(key){
var attrName = $attrs.$attr[key].replace("my-","");
$attrs.$set(attrName,$parse($attrs[key])($scope));
});
angular.element("#log").text(angular.element("#container").html());
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="ctrl">
<div id="container">
<div ng-model="mymodel" ng-selected="{{nothing}}" my-stack="someprop" ca-attr></div>
</div>
<div id="log"></div>
</div>
謝謝。看起來不錯 – Aminadav
您可以使用指令。下面是一個簡單的例子:
HTML
<div ng-app="myApp">
<div ui-foo="foo">foo scope variable: {{foo}}</div>
</div>
JS
angular.module('myApp', []).directive('uiFoo',
function() {
return {
restrict: 'EAC',
link: function($scope, element, attrs, controller) {
$scope.foo = attrs.uiFoo;
}
};
}
);
我建議你閱讀有關指示,這是關於這個問題的好文章:http://www.undefinednull.com/2014/02/11/mastering-the -spec-of-a-directive-in-angularjs/ – user2517028
我建議你不要將你的指令命名爲ng- *。請參閱第2個最佳實踐塊https://docs.angularjs.org/guide/directive#creating-directives –
否......除非核心指令實際存在,否則在'ng-'中沒有任何內容隱含 – charlietfl