我有以下代码:
的index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js"></script>
<script src="scripts/pandaApp.js"></script>
</head>
<body ng-app="pandaApp" ng-controller="pandaController">
<p ng-repeat="el in rainbow"><test color="{{el.color}}" ng-click="updateColor(el)"></test></p>
<li ng-repeat="el in rainbow">{{el.color}}</li>
{{dario.age}} {{dario.surname}}
</body>
</html>
pandaApp.js
var pandaApp = angular.module("pandaApp", ['ngRoute']);
pandaApp.controller('pandaController', ['$scope', function($scope) {
$scope.rainbow = [
{color:"red"},
{color:"orange"},
{color:"yellow"},
{color:"blue"}
];
$scope.updateColor = function(el) {
el.color="changed";
}
}]);
pandaApp.directive("test", function() {
return {
restrict:'E',
template:'<i>{{color}}</i>',
link: function(scope, el, attr){
console.log("print attributes value: " + attr.color );
scope.color=attr.color;
}
}
});
到目前为止,我在index.html中使用ng-repeat为彩虹列表中包含的每个对象创建一个“test”元素。这反过来显示值“颜色”。这很好用。但是,我添加了一个ng-click指令,以便每次单击一个元素时,其“color”属性的值变为“已更改”。
这反映在列表中,但不在指令'test'中。
我不知道为什么会这样。我认为<test color="{{el.color}}"
在更改指令时会更新指令中的参数颜色吗?
有什么建议吗?
的Dario
答案 0 :(得分:1)
属性是一个字符串,它不会更新。相反,您需要从范围到指令隔离范围的双向绑定:
pandaApp.directive("test", function() {
return {
restrict:'E',
template:'<i>{{color}}</i>',
scope: {
color: '='
},
link: function(scope, el, attr) {
}
}
});
答案 1 :(得分:1)
var pandaApp = angular.module("pandaApp",[]);
pandaApp.controller('pandaController', ['$scope', function($scope) {
$scope.rainbow = [
{color:"red"},
{color:"orange"},
{color:"yellow"},
{color:"blue"}
];
$scope.updateColor = function(el) {
el.color="changed";
console.log("Changed")
}
}]);
pandaApp.directive("test", function() {
return {
restrict:'E',
template:'<i>{{color}}</i>',
scope:{color:"@"},
link: function(scope, el, attr){
console.log("print attributes value: " + scope.color );
}
}
});