我可能只是在这里使自己感到困惑。但是我有一个结合了变量和文本的视图。而且我需要将整个内容存储为模型中的字符串。即。
<h3>
{{vars.color}} is my color: {{theme.color.black}};
</h3>
我希望能够将字符串保存到:
{{preference.string}} // as 'base is my color: #000'
我没有显示文字的问题。但是我想保存整个字符串。(好像我可以添加ng-model一样)到'h3'标签。但这是行不通的。
我应该在函数或指令中执行此操作吗?
提前致谢...
通常,从控制器接触DOM被认为是不好的。
但是,在您的情况下,我看不到其他选项,因为您只是从DOM中读取内容,而不以任何方式对其进行操作,所以还不错。
假设您已在控制器中呈现了文本,则可以$element
用来获取对元素的访问权限,然后获取文本内容。同样,这是不得已而为之,并且违反了Angular哲学。
var app = angular.module("myApp", [])
app.controller("HomeController", HomeController);
function HomeController($scope,$element) {
$scope.vars = {};
$scope.vars.color = "Black";
$scope.theme = {color:{}};
$scope.theme.color.black = "#000000";
$scope.snap = function(){
alert($element.find("h3").text()); // will alert the text
}
}
另外,您也可以使用将逻辑与控制器(以及使用的DOM)完全分离$compile
。这是一个相当长的示例,但是它使您可以窥探Angular的做事方式,这不需要应用程序。
var $inj = angular.injector(["ng"]); // get access to Angular's services
var template = "<h3>{{vars.color}} is my color: {{theme.color.black}}</h3>"
//now let's access the compilation service, and also a scope service and get a new scope.
var $compile = $inj.get("$compile");
var $scope = $inj.get("$rootScope").$new(true);
// put our stuff in this new scope
$scope.vars = {color:"White"};
$scope.theme = {color:{black:"#000000"}};
// add the template
var ngTemplate = $compile(angular.element(template));
var result = ngTemplate($scope);
$scope.$apply(); // tell angular to apply changes to the scope
console.log(result.text()); // now we have our rendered text.
// calling $destroy on the scope here is probably good ;)
但是,您确定要查找的不是局部视图吗?什么是目的的呢?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句