Angularjs directive
Angularjs directive
我想要一个类似于ng模型的属性指令。我只想额外地将一个输入字段值绑定到一个范围变量(只在一个方向上输入字段->范围变量)。所以我刚刚尝试了这个指令,但无论如何都无法调用该指令。
脚本:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
passivemodel: '='
},
link: function (scope, element, attrs) {
scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
console.log("passive model", newPassivemodel);
});
}
};
})
html:
<input data-passivemodel="keyword">
编辑:
嗯。。根据vilo20的回答,我遇到了一个非常奇怪的行为。
虽然此代码运行良好:<input data-ng-model="keyword" data-passivemodel="keyword">
这个没有(注意passivemodel的值):CCD_ 2。当然,我已经在控制器中定义了变量。
控制器:
.controller('SearchController', function($scope, $routeParams, $search) {
$scope.search = new $search();
$scope.keyword = "";
$scope.keyword2 = "";
})
伊迪丝2:这是一把小提琴http://jsfiddle.net/HB7LU/12107/
试试这个:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
passivemodel: '='
},
link: function (scope, element, attrs) {
console.log("passive model", scope.passivemodel);
$scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
//put your logic when passivemodel changed
});
}
};
})
希望它能帮助
编辑:这是一个plunkerhttp://plnkr.co/edit/T039I02ai5rBbiTAHfzv?p=preview
使用范围属性:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
"passivemodel": "="
},
link: function (scope, element, attrs) {
console.log("access passivemodel: ", scope.passivemodel);
}
};
})
最后就这么简单:
.directive('modelRed', [function(){
return {
require: 'ngModel',
restrict: 'A',
scope: {},
link: function (scope, element, attrs, ngModel) {
scope.$watch(function () {
return ngModel.$modelValue;
}, function(newValue) {
scope.$parent[attrs.modelRed] = newValue;
//console.log(attrs.modelRed, newValue, scope);
});
}
}
}])
在html:中
<p><input type="text" data-ng-model="testInput" data-model-red="redInput">{{redInput}}</p>
当然,您必须在$scope
对象中定义testInput
和redInput
。
相关文章:
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- Angularjs directive
- API for AngularJS Directive
- Angular2 $compile directive as AngularJS 1
- Bootstrap datepicker directive for angularjs
- AngularJS module.directive 没有一致响应
- Angularjs Directive For jQuery Cycle Plugin
- Angularjs: transclude directive template
- Angularjs directive and string.format
- AngularJS : ngRepeat in Directive with transcluded content
- 名为 directive angularjs 的变量
- 使用 Directive 通过指令注入 HTML,使用 AngularJS 进行数据绑定
- element.replaceWith in AngularJS directive
- Angularjs binding array element ng-repeat in directive
- Angularjs directive with ng-click
- AngularJS curstom directive and ngRepeat
- 如何在内部访问AngularJS Directive属性;在ng重复之外
- AngularJS ng-repeat custom directive
- 动态设置AngularJS Directive元素的属性
- AngularJS directive $destroy