Javascript 数据未显示在created指令中
我的html如下所示:Javascript 数据未显示在created指令中,javascript,angularjs,html,angularjs-directive,angular-directive,Javascript,Angularjs,Html,Angularjs Directive,Angular Directive,我的html如下所示: <body ng-app="customDirective"> <div ng-controller="anController"> Date format: <input ng-model="fooData"> <hr/> Current time is: <my-new-directive foo-Attr="{{fooData}}"></my-new-directive> </div>
<body ng-app="customDirective">
<div ng-controller="anController">
Date format: <input ng-model="fooData"> <hr/>
Current time is: <my-new-directive foo-Attr="{{fooData}}"></my-new-directive>
</div>
</body>
</html>
return {
restrict: 'AE', // allow it as element or attribute
link: link,
scope: {
fooAttr: '@'
}
};
我正在创建一个指令:
(function(angular) {
'use strict';
angular.module('customDirective', [])
.controller('anController', ['$scope', function($scope) {
$scope.fooData = 'Hello World!:)';
}])
.directive('myNewDirective', [function() {
function link(scope, element, attrs) {
var format,
timeoutId;
function updateValue() {
element.text(format);
}
scope.$watch(scope.fooData, function(value) {
format = value;
updateValue();
});
}
return {
restrict: 'A',
link: link,
scope: {
fooAttr: '@'
}
};
}]);
document.createElement('my-new-directive');
})(window.angular);
但若我在输入标记中写入新值,那个么在我的新指令中就不会发生任何事情
任何帮助都将不胜感激!我使用的是AngularJS 1.5.8。有几个错误
cammelCase
fooAttr
而不是fooAttr
@
(单向绑定),所以应该使用foo attr=“{{fooData}}”
<div ng-anController="anController">
到
并尝试遵循更好的命名约定,如app
name不应该有directive
后缀,而且directive
name也应该在@pankajParkar提到的camelcase
中
ng anController=“anController”
,似乎应该是ng controller=“anController”
scope.fooAttr
,而不是scope.fooData
我看到几个错误,指令过于复杂。 除以上所有评论外,这是错误的:
return {
restrict: 'A',
link: link,
scope: {
fooAttr: '@'
}
};
您可以限制指令在作为属性添加时起作用。
但是,在示例代码中:
Current time is: <my-new-directive foo-Attr="{{fooData}}"></my-new-directive>
或
此外,请删除以下内容:
document.createElement('my-new-directive');
查看此代码笔:
这应该会对你有所帮助。我已经使用了你的更正,但是如果我向
写信,那么什么都不会改变。请在我的问题中查看我的更新代码以及您的更正。document.createElement('my-new-directive')的位置正确吗代码>?请在我的问题中查看我的更新代码以及您的更正。document.createElement('my-new-directive')的位置正确吗代码>?为什么应该查看scope.fooAttr
而不是scope.fooData
?您可以看到Roy的codepen,在您的指令中,您不知道fooData,它是一个独立的范围,您只获得fooAttr,但是fooAttr
是与fooData
的bi绑定,因此您只能查看fooAttr
。非常感谢!你是我的英雄!谢谢!谢谢它非常有效!但是你为什么认为指令过于复杂?
return {
restrict: 'AE', // allow it as element or attribute
link: link,
scope: {
fooAttr: '@'
}
};
return {
restrict: 'E', // only element
link: link,
scope: {
fooAttr: '@'
}
};
document.createElement('my-new-directive');