从ngStyle中的函数检索值

时间:2014-11-19 12:40:28

标签: angularjs

我是angularjs的初学者,我确信必须有一个简单的解决方案,但我无法固定它。我试图通过函数获取元素的样式,但不成功。这是代码:

Script.js:
(function(angular) {
  'use strict';
angular.module('docsBindExample', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.color = "{'background-color':'red'}";
    $scope.fetchStyle = function(){
      return {'background-color':'red'};
    };
    $scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)';
  }]);
})(window.angular);

Index.html:
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example9-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
  <script src="script.js"></script>



</head>
<body ng-app="docsBindExample">
  <div ng-controller="Controller">
  Hello <input ng-model='name'> <hr/>
  <span ng-bind="name" ng-style="fetchColor()"></span> <br/>
  <span ng:bind="name"></span> <br/>
  <span ng_bind="name"></span> <br/>
  <span data-ng-bind="name"></span> <br/>
  <span x-ng-bind="name"></span> <br/>
</div>
</body>
</html>

我使用fetchColor()来获取span的颜色。有一些语法错误或其他什么?所有答复都赞赏

1 个答案:

答案 0 :(得分:0)

ng-style需要一个表达式。您还在标记中使用fetchColor(),但在控制器中使用fetchStyle()

尝试

<span ng-bind="name" ng-style="{{fetchStyle()}}"></span> <br/>
<span ng:bind="name" ng-style="{{color}}"></span> <br/>

此外,您正在为$scope.color

创建一个字符串

变化:

$scope.color = "{'background-color':'red'}";

$scope.color = {'background-color':'red'};

DEMO