How to split a predetermined angular variable into separate variable

时间:2017-07-29 02:05:42

标签: javascript html angularjs

I'm in the middle of working on a code that wants me to incorporate an inputted dimension as the width and height of the image displayed.

The dimension would be written as 300x250 and the height and width of the image would change accordingly to that.

The line of code I need to manipulate is:

<div ng-app="" ng-init="baseUrl='foo.img'">
  File name: <input style="width:225px" ng-model="filename" value="{{filename}}">

I can't change anything in that-- I just have to generate the image based on the filename i was given. I assumed that I could get away with something like:

<img style="width: {{filename}}px" src="{{baseUrl}}" alt="">

but the problem with this is that once an X is introduced in the width, it malfunctions. Any ideas? I can generate any sort of angular to spit out the result.

Edits: Malfunctions: meaning that once 300x is written the image disappears since 300x is not an actual size that CSS understands. I want something like 300x250 to be understood as width=300px and height=250px.

1 个答案:

答案 0 :(得分:1)

您可以根据*拆分尺寸并设置宽度和高度: -

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.width = 225;
  $scope.height = 300
  $scope.filename = $scope.width+'*'+$scope.height;
  $scope.buildDimensions = function(dim) {
    var res = dim.split("*");
    if(res[0] != undefined){
       $scope.width = res[0];
     }
     if(res[1] != undefined){
       $scope.height = res[1];
     }
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <div ng-init="baseUrl='https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'">
      File name: <input ng-change="buildDimensions(filename)" style="width:225px" ng-model="filename" value="{{filename}}">
      <img style="width: {{width}}px;height: {{height}}px" src="{{baseUrl}}" alt="">
    </div>