在下面的 HTML 中,我想从 Controller 中的范围变量中注入(inject)“src”值。
HTML:
<customdir filterby="name" src="imgName"></customdir>
Controller 中的$scope.imgName 变量有图像路径。
Java 语言:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($http, $scope) {
$scope.name = 'ready';
$scope.imgName = '~/Content/arrow-right-xxl.png';
)};
app.directive('customdir', function ($compile) {
var getTemplate = function (filter) {
switch (filter) {
case 'ready': return '<div class="col-lg-1" id="ready">' +
'<img src={{src}} style="height: 35px; width: 35px; margin-left: 0px; margin-top: 35px" />' +
'</div>';
default: return '<input type="text" ng-model="filterby" />';
}
}
return {
restrict: 'E',
scope: {
src: '@',
filterby: "="
},
link: function (scope, element, attrs) {
var el = $compile(getTemplate(scope.filterby))(scope);
element.replaceWith(el);
}
};
});
最佳答案
将您的指令更改为此代码
app.directive('customdir', function ($compile) {
var getTemplate = function (filter, src) {
switch (filter) {
case 'ready': return '<div class="col-lg-1" id="ready">' +
'<img src='+src+' style="height: 35px; width: 35px; margin-left: 0px; margin-top: 35px" />' +
'</div>';
default: return '<input type="text" ng-model="filterby" />';
}
}
return {
restrict: 'E',
scope: {
src: '=',
filterby: "="
},
link: function (scope, element, attrs) {
var el = $compile(getTemplate(scope.filterby, scope.src))(scope);
element.replaceWith(el);
}
};
});
将 scope.filterby 和 scope.src 直接传递给您的指令。
关于javascript - 图像源未与指令内的范围变量绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40837232/