有人可以解释为什么我的代码没有按预期工作吗?
我希望点击按钮后,文本应该更新。但显然,事实并非如此。
我真的很感激任何帮助。
x = angular.module('app', []);
x.directive("changer", function(myService){
return {
restrict: "E",
template: "<button>click</button>",
replace: true,
link: function (scope, elem, attrs) {
elem.click(function () {
myService.item1 = 'updated';
scope.$apply();
})
}
}
});
x.service('myService', function () {
var item = {'item1': 1, 'item2': 2};
return {
item : item,
};
});
x.controller('myController', function ($scope, myService) {
$scope.item = myService.item;
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="main.js"></script>
</head>
<body ng-controller='myController'>
<changer></changer>
{{item.item1}}
</body>
</html>
谢谢!
答案 0 :(得分:0)
更轻松,更好地使用&nbsp;点击&#39;在您的指令模板中,请参阅下面的演示
x = angular.module('app', []);
x.directive("changer", function(myService) {
return {
restrict: "E",
template: "<button ng-click='update()'>click</button>",
replace: true,
link: function(scope, elem, attrs) {
scope.update = function() {
myService.item.item1 = 'updated';
}
}
}
});
x.service('myService', function() {
var item = {
'item1': 1,
'item2': 2
};
return {
item: item,
};
});
x.controller('myController', function($scope, myService) {
$scope.item = myService.item;
$scope.test = "dfsf"
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="app">
<div ng-controller='myController'>
<pre>{{item| json}}</pre>
<changer></changer>
</div>
</div>
</body>
&#13;