Angularjs 将模板字符串转换为变量引用
我有一个如下所示的属性指令:Angularjs 将模板字符串转换为变量引用,angularjs,Angularjs,我有一个如下所示的属性指令: directive('syncFocusWith', function($timeout, $rootScope) { return { restrict: 'A', scope: { focusValue: "=syncFocusWith" }, link: function($scope, $element, attrs) { $scope.$
directive('syncFocusWith', function($timeout, $rootScope) {
return {
restrict: 'A',
scope: {
focusValue: "=syncFocusWith"
},
link: function($scope, $element, attrs) {
$scope.$watch("focusValue", function(currentValue, previousValue) {
console.log(previousValue);
console.log(currentValue);
if (currentValue === true && !previousValue) {
$element[0].focus();
} else if (currentValue === false && previousValue) {
$element[0].blur();
}
})
}
}
});
sync-focus-with="passwordfocus"
sync-focus-with="method+'passwordfocus'"
<simperium-auth method="create"></simperium-auth>
如果我设置如下值:
directive('syncFocusWith', function($timeout, $rootScope) {
return {
restrict: 'A',
scope: {
focusValue: "=syncFocusWith"
},
link: function($scope, $element, attrs) {
$scope.$watch("focusValue", function(currentValue, previousValue) {
console.log(previousValue);
console.log(currentValue);
if (currentValue === true && !previousValue) {
$element[0].focus();
} else if (currentValue === false && previousValue) {
$element[0].blur();
}
})
}
}
});
sync-focus-with="passwordfocus"
sync-focus-with="method+'passwordfocus'"
<simperium-auth method="create"></simperium-auth>
它很好用。Console.log将输出在控制器中设置的PasswordFocust的值
但我需要这样设置一个值:
directive('syncFocusWith', function($timeout, $rootScope) {
return {
restrict: 'A',
scope: {
focusValue: "=syncFocusWith"
},
link: function($scope, $element, attrs) {
$scope.$watch("focusValue", function(currentValue, previousValue) {
console.log(previousValue);
console.log(currentValue);
if (currentValue === true && !previousValue) {
$element[0].focus();
} else if (currentValue === false && previousValue) {
$element[0].blur();
}
})
}
}
});
sync-focus-with="passwordfocus"
sync-focus-with="method+'passwordfocus'"
<simperium-auth method="create"></simperium-auth>
方法从父指令传递,如下所示:
directive('syncFocusWith', function($timeout, $rootScope) {
return {
restrict: 'A',
scope: {
focusValue: "=syncFocusWith"
},
link: function($scope, $element, attrs) {
$scope.$watch("focusValue", function(currentValue, previousValue) {
console.log(previousValue);
console.log(currentValue);
if (currentValue === true && !previousValue) {
$element[0].focus();
} else if (currentValue === false && previousValue) {
$element[0].blur();
}
})
}
}
});
sync-focus-with="passwordfocus"
sync-focus-with="method+'passwordfocus'"
<simperium-auth method="create"></simperium-auth>
如果我这样设置值,angular会将其视为字符串,而不是范围中对象的引用。如何使其引用范围中的对象?在撕裂头发数小时后,我在发布以下内容后才意识到该如何操作:
sync-focus-with="this[method+'usernamefocus']"
是至少一种解决方案。将类似于[method+'usernamefocus']的对象表示法与HTML混合使用可能不推荐。 我认为您需要的是$scope。$eval:
JSFIDLE会有帮助。。