javascript - 在指令中使用链接和模板属性
问题描述
Wants to use the link function of the directive. Such that it should display a name and on click should change it to the new given name. but there is some error in my template property. w
Where do i get wrong?
JS code-
var app=angular.module("app",[]);
app.controller("myController",function($scope){
});
app.directive("myDirective",function(){
return{
restrict:"EA",
link: function($scope,element,attr){
$scope.name="Hello World";
$scope.changeName=function(newName){
$scope.name=newName;
}
},
template: '<span ng-click="changeName('Hi!')">current name:{{name}}</span>'
};
});
HTML code-
<hmtl>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
<script src="example4.js"></script>
</head>
<body ng-app="app">
<div ng-controller="myController">
<div my-directive ></div>
</div>
</body>
</hmtl>
首先,我将指令限制为“EA”。然后为范围提供一个名称,并为范围提供一个“changeName”函数。然后提供了一个模板以在单击时将初始化名称更改为 newName。
解决方案
只需使用 '+'hi'+'
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myController">
<w3-test-directive></w3-test-directive> </div>
<script>
var app = angular.module("myApp", []);
app.controller("myController",function($scope){
});
app.directive("w3TestDirective",function(){
return{
restrict:"EA",
link: function($scope,element,attr){
$scope.name="Hello World";
$scope.changeName=function(newName){
$scope.name=newName;
}
},
template: '<span ng-click="changeName('+'hi'+')">current name:{{name}}</span>'
};
});
</script>
</body>
</html>
推荐阅读
- javascript - 如何使用 phantomjs 截取网页的一部分?
- reactjs - 反应 - 运行开发服务器
- java - 如何让 Java 从 XML 文件中调用字符串(在 Android Studio 中)
- javascript - 如果对象的键值存在于其他对象中,如何替换它们?
- postgresql - 为具有一对多外键关系的对象构建 hasura-graphql 插入突变查询
- xamarin - Xamarin ListView 行非常小
- python-3.x - NameError:变量未定义
- c++ - 从数组中调用字段
- javascript - HTML - 内容未在选项卡中正确显示
- ruby - 动态获取定义的常量