2016-11-28 66 views
2

在下面的HTML中,我想从控制器中的范围变量注入'src'值。图像源与指令内的范围变量不绑定

HTML:

<customdir filterby="name" src="imgName"></customdir> 

$ scope.imgName变量在控制器具有的图像路径。

javascipt的:

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); 
    } 
}; 
}); 
+0

使用'img'标签 –

+0

中的'ng-src'和上面的代码,发生了什么?模板是否使用'input'元素进行渲染? –

+0

是它对输入元素的渲染,并且它能够使用** $ scope.name **进行绑定。但不适用于imgName ** img元素。 – Prashanth

回答

1

更改您的指令,该代码

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直接传递给您的指令。

+0

完美的工作!你能解释一下范围变量的'@'和'='的区别吗? – Prashanth

+0

你可以在这里得到答案http://stackoverflow.com/a/14063373/1572987 – errorare

0

试试这个

<customdir filterby="name" ng-src="imgName"></customdir> 
+0

谢谢Sujithrao,我已经试过了。它不工作! – Prashanth

+0

你是否在控制台中发现错误? – Sujithrao

+0

它显示“无法加载资源”,如果我喜欢上面的一样! – Prashanth

0

传递的imgName值象下面这样,因为你正在使用@您的指令src属性。

HTML:

<customdir filterby="name" src="{{imgName}}"></customdir> 

使用ng-src在像下面img标签:

的Javascript:

var getTemplate = function (filter) { 
    switch (filter) { 
     case 'ready': return '<div class="col-lg-1" id="ready">' + 
       '<img ng-src="{{src}}" style="height: 35px; width: 35px; margin-left: 0px; margin-top: 35px" />' + 
       '</div>'; 
     default: return '<input type="text" ng-model="filterby" />';   
    } 
}