Ame*_*ath 0 javascript angularjs angularjs-directive angular-ngmodel angularjs-ng-transclude
嗨,我正在处理指令,我需要在其中编辑 DOM 添加 ng-src 属性和模型。
这是我的 DOM
<edit-component>
<img src="images/logo.png" title="Hearty Wear" />
</edit-component>
Run Code Online (Sandbox Code Playgroud)
我需要结果 DOM
`<div>
<img src="images/logo.png" title="Hearty Wear" ng-src={{myModel}} />
</div> `
Run Code Online (Sandbox Code Playgroud)
这样当我用数据更新 myModel 时,图像应该更新
更新
sam.directive('editComponent', function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
templateUrl: "imageTemplate.html",
link: function(scope, element, attb, ctrl, transclude) {
scope.data = function() {
var imagedata;
imagedata = arguments[5];
scope.imageModel = imagedata.base64;
return element.find('img').attr('src', "data:image/png;base64," + imagedata.base64);
};
}
};
});
我还需要先前的src属性值来显示现有图像。
现在我正在手动更新src属性。我需要可以通过模型变量更新的解决方案
谢谢
在长时间阅读各种博客和站点中有关 AngularJS 指令的文档之后。
我刚开始知道完整的指令流程
流量将从
编译 -> 控制器 -> preLink -> postLink 或 (Link)
如果您想在编译阶段添加angular(ng-model, ng-style,ng-src) 的任何核心指令
var app;
app = angular.module('App', []);
app.directive('myDirective', [
'$compile', function($compile) { // Crucial Part
return {
scope: true,
compile: function(element, attrs) {
element.attr('ng-src', '{{imageModel}}');
element.attr('ng-click', 'updateImage()');
element.removeAttr('my-directive'); // Crucial Part
return {
pre: function(scope, ele, attb) {},
post: function(scope, ele, attb) {
$compile(ele)(scope);
return scope.updateImage = function() {
return scope.imageModel = "http://www.google.com/logos/doodles/2015/halet-cambels-99th-birthday-6544342839721984-hp2x.png";
};
}
};
},
controller: function($scope, $element, $attrs) {
return $scope.imageModel = null;
}
};
}
]);Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
img {
max-width: 100%;
}
</style>
</head>
<body ng-app='App'>
<img src="https://www.google.co.in/images/srpr/logo11w.png" alt="" my-directive>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
我将解释其中涉及的必要步骤。
第一阶段(编译):-
在这个阶段添加你想要的核心角度指令或自定义指令
element.attr('ng-src', '{{imageModel}}'); // For dynamic image url changes
element.attr('ng-click', 'updateImage()'); // The trigger to update image
element.removeAttr('my-directive'); // **Crucial step please remove your custom directive attribute**
Run Code Online (Sandbox Code Playgroud)
如果您在 $compile() 期间不删除您的自定义指令,它将无限次循环
第二阶段(控制器):-
在这些阶段定义您需要的所有模型和功能(我知道我已经在 postLink 中定义了 updateImage() 。它也有效!)
$scope.imageModel = null // 初始化
第三阶段(链接):- 顺序是先 preLink 然后 postLink 。我没有在预链接中定义任何东西。
postLink :- $compile(element)(scope)。这实际上将绑定编译元素中涉及的所有指令,并动态绑定它们。(vola)。一切都按预期工作。
谢谢。如果你觉得我遗漏了一些要点或误解了这个概念,请随时更新它。
JSBin 链接https://jsbin.com/parote/edit?html,js,output
| 归档时间: |
|
| 查看次数: |
3643 次 |
| 最近记录: |