我是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的颜色。有一些语法错误或其他什么?所有答复都赞赏
答案 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 强>