Javascript Angularjs指令
我想要一个属性指令,有点类似于ng模型。我只想另外将输入字段值绑定到范围变量(仅在一个方向上,输入字段->范围变量)。因此,我刚刚尝试了这个指令,但无论如何都无法调用该指令 脚本:Javascript Angularjs指令,javascript,angularjs,Javascript,Angularjs,我想要一个属性指令,有点类似于ng模型。我只想另外将输入字段值绑定到范围变量(仅在一个方向上,输入字段->范围变量)。因此,我刚刚尝试了这个指令,但无论如何都无法调用该指令 脚本: .directive('passivemodel', function () { return { restrict: "A", scope: { passivemodel: '=' }, link: function (scope, element, attrs)
.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:
Edit2:这里有一个fiddle使用scope属性:
.directive('passivemodel', function () {
return {
restrict: "A",
scope: {
"passivemodel": "="
},
link: function (scope, element, attrs) {
console.log("access passivemodel: ", scope.passivemodel);
}
};
})
试试这个:
.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
});
}
};
})
希望能有帮助
编辑:这是一个扑通声最后它就这么简单:
.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>
{{redInput}
当然,您必须在
$scope
对象中定义testInput
和redInput
。是的,这是有效的!但现在我的范围只限于指令,对吗?现在如何访问控制器作用域?因为“=”两个作用域都链接(绑定)。尝试从指令中更改被动模式-您将看到它在父范围中也被更改。2分钟后接受它。但我仍然有一个问题,请查看我的编辑。我正在寻找,你能创建一些JSFIDLE或plunker吗?您在控制台中是否有任何错误?在plunker olny中,关键字“正在工作”关键字“2”什么也没做。在我的小提琴中,当我使用被动模型时,甚至连关键字都不起作用。看看我在回答中为你做的扑救
.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);
});
}
}
}])
<p><input type="text" data-ng-model="testInput" data-model-red="redInput">{{redInput}}</p>