2016-11-28 21 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" />';   
    } 
}