Eti*_*oël 5 javascript jquery angularjs angularjs-directive
我正在创建一个包含许多不同问题的清道夫编辑器.而且,每个问题可以是不同类型的.因此,我有一系列问题,我做了一个ng-repeat来显示所有问题.
为此,我有一个代表问题的javascript对象.这个问题可以通过不同的问题类型继承.
我有一个特定的问题类型,即slidingPuzzle需要上传图像.我的问题到了这里,我希望能够在输入文件发生变化时调用此对象内的函数.
我想在这里强调它不能是在范围内声明的一般函数!
这是我的结构的样子(http://plnkr.co/edit/lnJ8rAlpP0xJ3aM2HZ7o?p=preview):
HTML:
<div class="question" ng-repeat="question in scavengerHunt.questions">
<div class="chooseQuestionType">
Question type:
<select ng-change="question.setChild()" ng-model="question.subClass">
<option value="slidingPuzzleQuestion">slidingPuzzleQuestion</option>
</select>
</div>
<div class="questionContainer">
<div class="puzzleContainer">
<input type="file" name="image" id="puzzleContainerImage" ng-file-select="question.child.imageFileSelected()">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
AngularJS模型:
var scavengerHuntApp = angular.module('scavengerHuntApp', []);
scavengerHuntApp.controller('QuestionsCtrl', function ($scope) {
function ScavengerHunt() {
var self = this;
self.questions = [];
self.addQuestion = function(question) {
self.questions.push(question);
}
}
function Question() {
var self = this;
self.id = 0;
self.subClass = "slidingPuzzleQuestion";
self.child = "";
self.setChild = function() {
var type = self.subClass;
if(type == 'slidingPuzzleQuestion'){
self.child = new SlidingPuzzleQuestion();
}
}
}
function SlidingPuzzleQuestion() {
var self = this;
self.imageFileSelected = function () {
console.log()
};
}
//Utilities function
$scope.addEmptyQuestion = function() {
$scope.scavengerHunt.addQuestion(new Question());
}
$scope.scavengerHunt = new ScavengerHunt();
$scope.addEmptyQuestion();
});
Run Code Online (Sandbox Code Playgroud)
AngularJS指令
到目前为止,我认为我可能不得不使用AngularJS指令,因为ng-change目前不能用于输入文件(https://github.com/angular/angular.js/issues/1375).因此,以下代码不起作用,因为在html标记中ng-file-select="question.child.imageFileSelected()",我有一个在尝试将元素绑定到函数时丢失的上下文.
scavengerHuntApp.directive("ngFileSelect",function(){
return {
link: function (scope, element, attrs) {
console.log(scope);
console.log(element);
var onChangeFunc = element.scope()[attrs.customOnChange];
element.bind('change', onChangeFunc);
}
}
});
Run Code Online (Sandbox Code Playgroud)
那么,有没有办法在html代码中传递当前上下文以将其绑定到特定对象?
我希望一切都清楚,如果不让我知道,我会尽可能地澄清!
小智 4
好的,看看这个笨蛋:http://plnkr.co/edit/qPK6EmAkt39QoZFZ5Sa3 ?p=preview
我删除了您的一些代码,只是为了让您了解底层发生了什么。
您可以使用符号将隔离范围与回调属性绑定结合&使用。它的作用是将属性中的表达式注册为指令的隔离范围内的可调用函数。
规则是:
您注册隔离范围
scope : {
myAttr : "&"
}
Run Code Online (Sandbox Code Playgroud)您在表单中指定属性
my-attr="object.objectMethod(param1, param2)"
Run Code Online (Sandbox Code Playgroud)objectMethodAngular使用可调用包装器包装
当需要时,您可以像这样调用包装器:
scope.myAttr({param1: "value", param2:"value"})
Run Code Online (Sandbox Code Playgroud)object.objectMethod具有指定参数的实际调用